NativeCrypto.java revision f24ba0620d88b7d71ddb089b97d29fb1b073718d
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.conscrypt;
18
19import java.io.FileDescriptor;
20import java.io.IOException;
21import java.io.OutputStream;
22import java.net.SocketTimeoutException;
23import java.security.MessageDigest;
24import java.security.NoSuchAlgorithmException;
25import java.security.PrivateKey;
26import java.security.Provider;
27import java.security.Security;
28import java.security.Signature;
29import java.security.SignatureException;
30import java.security.cert.CertificateEncodingException;
31import java.security.cert.CertificateException;
32import java.security.cert.CertificateParsingException;
33import java.security.interfaces.DSAPrivateKey;
34import java.security.interfaces.ECPrivateKey;
35import java.security.interfaces.RSAPrivateKey;
36import java.util.ArrayList;
37import java.util.Calendar;
38import java.util.HashMap;
39import java.util.LinkedHashMap;
40import java.util.List;
41import java.util.Map;
42import javax.crypto.BadPaddingException;
43import javax.crypto.Cipher;
44import javax.crypto.IllegalBlockSizeException;
45import javax.crypto.NoSuchPaddingException;
46import javax.net.ssl.SSLException;
47import javax.security.auth.x500.X500Principal;
48
49/**
50 * Provides the Java side of our JNI glue for OpenSSL.
51 */
52public final class NativeCrypto {
53
54    // --- OpenSSL library initialization --------------------------------------
55    static {
56        /*
57         * If we're compiled as part of Android, should use a different JNI
58         * library name. Detect this by looking for the jarjar'd package name.
59         */
60        if ("com.android.org.conscrypt".equals(NativeCrypto.class.getPackage().getName())) {
61            System.loadLibrary("javacrypto");
62        } else {
63            System.loadLibrary("conscrypt_jni");
64        }
65
66        clinit();
67    }
68
69    private native static void clinit();
70
71    // --- ENGINE functions ----------------------------------------------------
72    public static native void ENGINE_load_dynamic();
73
74    public static native long ENGINE_by_id(String id);
75
76    public static native int ENGINE_add(long e);
77
78    public static native int ENGINE_init(long e);
79
80    public static native int ENGINE_finish(long e);
81
82    public static native int ENGINE_free(long e);
83
84    public static native long ENGINE_load_private_key(long e, String key_id);
85
86    public static native String ENGINE_get_id(long engineRef);
87
88    public static native int ENGINE_ctrl_cmd_string(long engineRef, String cmd, String arg,
89            int cmd_optional);
90
91    // --- DSA/RSA public/private key handling functions -----------------------
92
93    public static native long EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
94                                               byte[] pub_key, byte[] priv_key);
95
96    public static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
97            byte[] dmp1, byte[] dmq1, byte[] iqmp);
98
99    public static native long EVP_PKEY_new_mac_key(int type, byte[] key);
100
101    public static native int EVP_PKEY_size(long pkey);
102
103    public static native int EVP_PKEY_type(long pkey);
104
105    public static native String EVP_PKEY_print_public(long pkeyRef);
106
107    public static native String EVP_PKEY_print_private(long pkeyRef);
108
109    public static native void EVP_PKEY_free(long pkey);
110
111    public static native int EVP_PKEY_cmp(long pkey1, long pkey2);
112
113    public static native byte[] i2d_PKCS8_PRIV_KEY_INFO(long pkey);
114
115    public static native long d2i_PKCS8_PRIV_KEY_INFO(byte[] data);
116
117    public static native byte[] i2d_PUBKEY(long pkey);
118
119    public static native long d2i_PUBKEY(byte[] data);
120
121    public static native long getRSAPrivateKeyWrapper(RSAPrivateKey key, byte[] modulus);
122
123    public static native long getDSAPrivateKeyWrapper(DSAPrivateKey key);
124
125    public static native long getECPrivateKeyWrapper(ECPrivateKey key, long ecGroupRef);
126
127    public static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
128
129    public static native int RSA_size(long pkey);
130
131    public static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, long pkey,
132            int padding);
133
134    public static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, long pkey,
135            int padding) throws BadPaddingException, SignatureException;
136
137    public static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, long pkey,
138            int padding);
139
140    public static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, long pkey,
141            int padding) throws BadPaddingException, SignatureException;
142
143    /**
144     * @return array of {n, e}
145     */
146    public static native byte[][] get_RSA_public_params(long rsa);
147
148    /**
149     * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
150     */
151    public static native byte[][] get_RSA_private_params(long rsa);
152
153    public static native long DSA_generate_key(int primeBits, byte[] seed, byte[] g, byte[] p,
154            byte[] q);
155
156    /**
157     * @return array of {g, p, q, y(pub), x(priv)}
158     */
159    public static native byte[][] get_DSA_params(long dsa);
160
161    public static native void set_DSA_flag_nonce_from_hash(long dsa);
162
163    public static native byte[] i2d_RSAPublicKey(long rsa);
164
165    public static native byte[] i2d_RSAPrivateKey(long rsa);
166
167    public static native byte[] i2d_DSAPublicKey(long dsa);
168
169    public static native byte[] i2d_DSAPrivateKey(long dsa);
170
171    // --- DH public/private key handling functions ----------------------------
172
173    public static native long EVP_PKEY_new_DH(byte[] p, byte[] g, byte[] pub_key, byte[] priv_key);
174
175    public static native long DH_generate_key(int primeBits, int generator);
176
177    /**
178     * @return array of {p, g, y(pub), x(priv)}
179     */
180    public static native byte[][] get_DH_params(long dh);
181
182    // --- EC functions --------------------------
183
184    /**
185     * Used to request EC_GROUP_new_curve_GFp to EC_GROUP_new_curve
186     */
187    public static final int EC_CURVE_GFP = 1;
188
189    /**
190     * Used to request EC_GROUP_new_curve_GF2m to EC_GROUP_new_curve
191     */
192    public static final int EC_CURVE_GF2M = 2;
193
194    /**
195     * EC_GROUP_set_asn1_flag: indicates an EC_GROUP is a NamedCurve.
196     */
197    public static final int OPENSSL_EC_NAMED_CURVE = 0x001;
198
199    /**
200     * EC_GROUP_set_point_conversion_form: indicates compressed ASN.1 format
201     */
202    public static final int POINT_CONVERSION_COMPRESSED = 2;
203
204    /**
205     * EC_GROUP_set_point_conversion_form: indicates uncompressed ASN.1 format
206     */
207    public static final int POINT_CONVERSION_UNCOMPRESSED = 4;
208
209    /**
210     * EC_GROUP_set_point_conversion_form: indicates hybrid ASN.1 format
211     */
212    public static final int POINT_CONVERSION_HYBRID = 4;
213
214    public static native long EVP_PKEY_new_EC_KEY(long groupRef, long pubkeyRef, byte[] privkey);
215
216    public static native long EC_GROUP_new_by_curve_name(String curveName);
217
218    public static native long EC_GROUP_new_curve(int type, byte[] p, byte[] a, byte[] b);
219
220    public static native long EC_GROUP_dup(long groupRef);
221
222    public static native void EC_GROUP_set_asn1_flag(long groupRef, int flag);
223
224    public static native void EC_GROUP_set_point_conversion_form(long groupRef, int form);
225
226    public static native String EC_GROUP_get_curve_name(long groupRef);
227
228    public static native byte[][] EC_GROUP_get_curve(long groupRef);
229
230    public static native void EC_GROUP_clear_free(long ctx);
231
232    public static native boolean EC_GROUP_cmp(long ctx1, long ctx2);
233
234    public static native void EC_GROUP_set_generator(long groupCtx, long pointCtx, byte[] n, byte[] h);
235
236    public static native long EC_GROUP_get_generator(long groupCtx);
237
238    public static native int get_EC_GROUP_type(long groupCtx);
239
240    public static native byte[] EC_GROUP_get_order(long groupCtx);
241
242    public static native int EC_GROUP_get_degree(long groupCtx);
243
244    public static native byte[] EC_GROUP_get_cofactor(long groupCtx);
245
246    public static native long EC_POINT_new(long groupRef);
247
248    public static native void EC_POINT_clear_free(long pointRef);
249
250    public static native boolean EC_POINT_cmp(long groupRef, long pointRef1, long pointRef2);
251
252    public static native byte[][] EC_POINT_get_affine_coordinates(long groupCtx, long pointCtx);
253
254    public static native void EC_POINT_set_affine_coordinates(long groupCtx, long pointCtx, byte[] x,
255            byte[] y);
256
257    public static native long EC_KEY_generate_key(long groupRef);
258
259    public static native long EC_KEY_get0_group(long pkeyRef);
260
261    public static native byte[] EC_KEY_get_private_key(long keyRef);
262
263    public static native long EC_KEY_get_public_key(long keyRef);
264
265    public static native void EC_KEY_set_nonce_from_hash(long keyRef, boolean enabled);
266
267    public static native int ECDH_compute_key(
268            byte[] out, int outOffset, long publicKeyRef, long privateKeyRef);
269
270    // --- Message digest functions --------------
271
272    public static native long EVP_get_digestbyname(String name);
273
274    public static native int EVP_MD_size(long evp_md);
275
276    public static native int EVP_MD_block_size(long evp_md);
277
278    // --- Message digest context functions --------------
279
280    public static native long EVP_MD_CTX_create();
281
282    public static native void EVP_MD_CTX_init(OpenSSLDigestContext ctx);
283
284    public static native void EVP_MD_CTX_destroy(long ctx);
285
286    public static native int EVP_MD_CTX_copy(OpenSSLDigestContext dst_ctx,
287            OpenSSLDigestContext src_ctx);
288
289    // --- Digest handling functions -------------------------------------------
290
291    public static native int EVP_DigestInit(OpenSSLDigestContext ctx, long evp_md);
292
293    public static native void EVP_DigestUpdate(OpenSSLDigestContext ctx, byte[] buffer,
294            int offset, int length);
295
296    public static native int EVP_DigestFinal(OpenSSLDigestContext ctx, byte[] hash, int offset);
297
298    // --- MAC handling functions ----------------------------------------------
299
300    public static native void EVP_DigestSignInit(OpenSSLDigestContext evp_md_ctx, long evp_md,
301            long evp_pkey);
302
303    public static native void EVP_DigestSignUpdate(OpenSSLDigestContext evp_md_ctx, byte[] in);
304
305    public static native byte[] EVP_DigestSignFinal(OpenSSLDigestContext evp_md_ctx);
306
307    // --- Signature handling functions ----------------------------------------
308
309    public static native int EVP_SignInit(OpenSSLDigestContext ctx, long evpRef);
310
311    public static native void EVP_SignUpdate(OpenSSLDigestContext ctx, byte[] buffer,
312                                               int offset, int length);
313
314    public static native int EVP_SignFinal(OpenSSLDigestContext ctx, byte[] signature, int offset,
315            long key);
316
317    public static native int EVP_VerifyInit(OpenSSLDigestContext ctx, long evpRef);
318
319    public static native void EVP_VerifyUpdate(OpenSSLDigestContext ctx, byte[] buffer,
320                                               int offset, int length);
321
322    public static native int EVP_VerifyFinal(OpenSSLDigestContext ctx, byte[] signature,
323                                             int offset, int length, long key);
324
325
326    // --- Block ciphers -------------------------------------------------------
327
328    public static native long EVP_get_cipherbyname(String string);
329
330    public static native void EVP_CipherInit_ex(long ctx, long evpCipher, byte[] key, byte[] iv,
331            boolean encrypting);
332
333    public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
334            int inOffset, int inLength);
335
336    public static native int EVP_CipherFinal_ex(long ctx, byte[] out, int outOffset)
337            throws BadPaddingException, IllegalBlockSizeException;
338
339    public static native int EVP_CIPHER_iv_length(long evpCipher);
340
341    public static native long EVP_CIPHER_CTX_new();
342
343    public static native int EVP_CIPHER_CTX_block_size(long ctx);
344
345    public static native int get_EVP_CIPHER_CTX_buf_len(long ctx);
346
347    public static native void EVP_CIPHER_CTX_set_padding(long ctx, boolean enablePadding);
348
349    public static native void EVP_CIPHER_CTX_set_key_length(long ctx, int keyBitSize);
350
351    public static native void EVP_CIPHER_CTX_cleanup(long ctx);
352
353    // --- RAND seeding --------------------------------------------------------
354
355    public static final int RAND_SEED_LENGTH_IN_BYTES = 1024;
356
357    public static native void RAND_seed(byte[] seed);
358
359    public static native int RAND_load_file(String filename, long max_bytes);
360
361    public static native void RAND_bytes(byte[] output);
362
363    // --- ASN.1 objects -------------------------------------------------------
364
365    public static native int OBJ_txt2nid(String oid);
366
367    public static native String OBJ_txt2nid_longName(String oid);
368
369    public static native String OBJ_txt2nid_oid(String oid);
370
371    // --- X509_NAME -----------------------------------------------------------
372
373    public static int X509_NAME_hash(X500Principal principal) {
374        return X509_NAME_hash(principal, "SHA1");
375    }
376    public static int X509_NAME_hash_old(X500Principal principal) {
377        return X509_NAME_hash(principal, "MD5");
378    }
379    private static int X509_NAME_hash(X500Principal principal, String algorithm) {
380        try {
381            byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
382            int offset = 0;
383            return (((digest[offset++] & 0xff) <<  0) |
384                    ((digest[offset++] & 0xff) <<  8) |
385                    ((digest[offset++] & 0xff) << 16) |
386                    ((digest[offset  ] & 0xff) << 24));
387        } catch (NoSuchAlgorithmException e) {
388            throw new AssertionError(e);
389        }
390    }
391
392    public static native String X509_NAME_print_ex(long x509nameCtx, long flags);
393
394    // --- X509 ----------------------------------------------------------------
395
396    /** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
397    public static final int GN_STACK_SUBJECT_ALT_NAME = 1;
398
399    /**
400     * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
401     * extension.
402     */
403    public static final int GN_STACK_ISSUER_ALT_NAME = 2;
404
405    /**
406     * Used to request only non-critical types in get_X509*_ext_oids.
407     */
408    public static final int EXTENSION_TYPE_NON_CRITICAL = 0;
409
410    /**
411     * Used to request only critical types in get_X509*_ext_oids.
412     */
413    public static final int EXTENSION_TYPE_CRITICAL = 1;
414
415    public static native long d2i_X509_bio(long bioCtx);
416
417    public static native long d2i_X509(byte[] encoded);
418
419    public static native long PEM_read_bio_X509(long bioCtx);
420
421    public static native byte[] i2d_X509(long x509ctx);
422
423    /** Takes an X509 context not an X509_PUBKEY context. */
424    public static native byte[] i2d_X509_PUBKEY(long x509ctx);
425
426    public static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
427
428    public static native long[] ASN1_seq_unpack_X509_bio(long bioRef);
429
430    public static native void X509_free(long x509ctx);
431
432    public static native int X509_cmp(long x509ctx1, long x509ctx2);
433
434    public static native int get_X509_hashCode(long x509ctx);
435
436    public static native void X509_print_ex(long bioCtx, long x509ctx, long nmflag, long certflag);
437
438    public static native byte[] X509_get_issuer_name(long x509ctx);
439
440    public static native byte[] X509_get_subject_name(long x509ctx);
441
442    public static native String get_X509_sig_alg_oid(long x509ctx);
443
444    public static native byte[] get_X509_sig_alg_parameter(long x509ctx);
445
446    public static native boolean[] get_X509_issuerUID(long x509ctx);
447
448    public static native boolean[] get_X509_subjectUID(long x509ctx);
449
450    public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException;
451
452    public static native String get_X509_pubkey_oid(long x509ctx);
453
454    public static native byte[] X509_get_ext_oid(long x509ctx, String oid);
455
456    public static native String[] get_X509_ext_oids(long x509ctx, int critical);
457
458    public static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, int type)
459            throws CertificateParsingException;
460
461    public static native boolean[] get_X509_ex_kusage(long x509ctx);
462
463    public static native String[] get_X509_ex_xkusage(long x509ctx);
464
465    public static native int get_X509_ex_pathlen(long x509ctx);
466
467    public static native long X509_get_notBefore(long x509ctx);
468
469    public static native long X509_get_notAfter(long x509ctx);
470
471    public static native long X509_get_version(long x509ctx);
472
473    public static native byte[] X509_get_serialNumber(long x509ctx);
474
475    public static native void X509_verify(long x509ctx, long pkeyCtx) throws BadPaddingException;
476
477    public static native byte[] get_X509_cert_info_enc(long x509ctx);
478
479    public static native byte[] get_X509_signature(long x509ctx);
480
481    public static native int get_X509_ex_flags(long x509ctx);
482
483    public static native int X509_check_issued(long ctx, long ctx2);
484
485    // --- X509 EXFLAG ---------------------------------------------------------
486
487    public static final int EXFLAG_CA = 0x10;
488
489    public static final int EXFLAG_CRITICAL = 0x200;
490
491    // --- PKCS7 ---------------------------------------------------------------
492
493    /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
494    public static final int PKCS7_CERTS = 1;
495
496    /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
497    public static final int PKCS7_CRLS = 2;
498
499    /** Returns an array of X509 or X509_CRL pointers. */
500    public static native long[] d2i_PKCS7_bio(long bioCtx, int which);
501
502    /** Returns an array of X509 or X509_CRL pointers. */
503    public static native byte[] i2d_PKCS7(long[] certs);
504
505    /** Returns an array of X509 or X509_CRL pointers. */
506    public static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
507
508    // --- X509_CRL ------------------------------------------------------------
509
510    public static native long d2i_X509_CRL_bio(long bioCtx);
511
512    public static native long PEM_read_bio_X509_CRL(long bioCtx);
513
514    public static native byte[] i2d_X509_CRL(long x509CrlCtx);
515
516    public static native void X509_CRL_free(long x509CrlCtx);
517
518    public static native void X509_CRL_print(long bioCtx, long x509CrlCtx);
519
520    public static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx);
521
522    public static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx);
523
524    public static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx);
525
526    /** Returns X509_REVOKED reference that is not duplicated! */
527    public static native long X509_CRL_get0_by_cert(long x509CrlCtx, long x509Ctx);
528
529    /** Returns X509_REVOKED reference that is not duplicated! */
530    public static native long X509_CRL_get0_by_serial(long x509CrlCtx, byte[] serial);
531
532    /** Returns an array of X509_REVOKED that are owned by the caller. */
533    public static native long[] X509_CRL_get_REVOKED(long x509CrlCtx);
534
535    public static native String[] get_X509_CRL_ext_oids(long x509ctx, int critical);
536
537    public static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, String oid);
538
539    public static native long X509_CRL_get_version(long x509CrlCtx);
540
541    public static native long X509_CRL_get_ext(long x509CrlCtx, String oid);
542
543    public static native byte[] get_X509_CRL_signature(long x509ctx);
544
545    public static native void X509_CRL_verify(long x509CrlCtx, long pkeyCtx);
546
547    public static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx);
548
549    public static native long X509_CRL_get_lastUpdate(long x509CrlCtx);
550
551    public static native long X509_CRL_get_nextUpdate(long x509CrlCtx);
552
553    // --- X509_REVOKED --------------------------------------------------------
554
555    public static native long X509_REVOKED_dup(long x509RevokedCtx);
556
557    public static native byte[] i2d_X509_REVOKED(long x509RevokedCtx);
558
559    public static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical);
560
561    public static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid);
562
563    public static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx);
564
565    public static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid);
566
567    /** Returns ASN1_TIME reference. */
568    public static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx);
569
570    public static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx);
571
572    // --- X509_EXTENSION ------------------------------------------------------
573
574    public static native int X509_supported_extension(long x509ExtensionRef);
575
576    // --- ASN1_TIME -----------------------------------------------------------
577
578    public static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal);
579
580    // --- BIO stream creation -------------------------------------------------
581
582    public static native long create_BIO_InputStream(OpenSSLBIOInputStream is);
583
584    public static native long create_BIO_OutputStream(OutputStream os);
585
586    public static native int BIO_read(long bioRef, byte[] buffer);
587
588    public static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
589            throws IOException;
590
591    public static native void BIO_free_all(long bioRef);
592
593    // --- SSL handling --------------------------------------------------------
594
595    private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
596    private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
597    private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
598    private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
599
600    public static final Map<String, String> OPENSSL_TO_STANDARD_CIPHER_SUITES
601            = new HashMap<String, String>();
602    public static final Map<String, String> STANDARD_TO_OPENSSL_CIPHER_SUITES
603            = new LinkedHashMap<String, String>();
604
605    private static void add(String standard, String openssl) {
606        OPENSSL_TO_STANDARD_CIPHER_SUITES.put(openssl, standard);
607        STANDARD_TO_OPENSSL_CIPHER_SUITES.put(standard, openssl);
608    }
609
610    /**
611     * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
612     * indication signaling cipher suite value. It is not a real
613     * cipher suite. It is just an indication in the default and
614     * supported cipher suite lists indicates that the implementation
615     * supports secure renegotiation.
616     *
617     * In the RI, its presence means that the SCSV is sent in the
618     * cipher suite list to indicate secure renegotiation support and
619     * its absense means to send an empty TLS renegotiation info
620     * extension instead.
621     *
622     * However, OpenSSL doesn't provide an API to give this level of
623     * control, instead always sending the SCSV and always including
624     * the empty renegotiation info if TLS is used (as opposed to
625     * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
626     * be passed for compatibility as to provide the hint that we
627     * support secure renegotiation.
628     */
629    public static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV
630            = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
631
632    static {
633        add("SSL_RSA_WITH_RC4_128_MD5",              "RC4-MD5");
634        add("SSL_RSA_WITH_RC4_128_SHA",              "RC4-SHA");
635        add("TLS_RSA_WITH_AES_128_CBC_SHA",          "AES128-SHA");
636        add("TLS_RSA_WITH_AES_256_CBC_SHA",          "AES256-SHA");
637        add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",       "ECDH-ECDSA-RC4-SHA");
638        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",   "ECDH-ECDSA-AES128-SHA");
639        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",   "ECDH-ECDSA-AES256-SHA");
640        add("TLS_ECDH_RSA_WITH_RC4_128_SHA",         "ECDH-RSA-RC4-SHA");
641        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",     "ECDH-RSA-AES128-SHA");
642        add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",     "ECDH-RSA-AES256-SHA");
643        add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",      "ECDHE-ECDSA-RC4-SHA");
644        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",  "ECDHE-ECDSA-AES128-SHA");
645        add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",  "ECDHE-ECDSA-AES256-SHA");
646        add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",        "ECDHE-RSA-RC4-SHA");
647        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",    "ECDHE-RSA-AES128-SHA");
648        add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",    "ECDHE-RSA-AES256-SHA");
649        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",      "DHE-RSA-AES128-SHA");
650        add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA",      "DHE-RSA-AES256-SHA");
651        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",      "DHE-DSS-AES128-SHA");
652        add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA",      "DHE-DSS-AES256-SHA");
653        add("SSL_RSA_WITH_3DES_EDE_CBC_SHA",         "DES-CBC3-SHA");
654        add("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",  "ECDH-ECDSA-DES-CBC3-SHA");
655        add("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",    "ECDH-RSA-DES-CBC3-SHA");
656        add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "ECDHE-ECDSA-DES-CBC3-SHA");
657        add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",   "ECDHE-RSA-DES-CBC3-SHA");
658        add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",     "EDH-RSA-DES-CBC3-SHA");
659        add("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",     "EDH-DSS-DES-CBC3-SHA");
660        add("SSL_RSA_WITH_DES_CBC_SHA",              "DES-CBC-SHA");
661        add("SSL_DHE_RSA_WITH_DES_CBC_SHA",          "EDH-RSA-DES-CBC-SHA");
662        add("SSL_DHE_DSS_WITH_DES_CBC_SHA",          "EDH-DSS-DES-CBC-SHA");
663        add("SSL_RSA_EXPORT_WITH_RC4_40_MD5",        "EXP-RC4-MD5");
664        add("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",     "EXP-DES-CBC-SHA");
665        add("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-RSA-DES-CBC-SHA");
666        add("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-DSS-DES-CBC-SHA");
667        add("SSL_RSA_WITH_NULL_MD5",                 "NULL-MD5");
668        add("SSL_RSA_WITH_NULL_SHA",                 "NULL-SHA");
669        add("TLS_ECDH_ECDSA_WITH_NULL_SHA",          "ECDH-ECDSA-NULL-SHA");
670        add("TLS_ECDH_RSA_WITH_NULL_SHA",            "ECDH-RSA-NULL-SHA");
671        add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",         "ECDHE-ECDSA-NULL-SHA");
672        add("TLS_ECDHE_RSA_WITH_NULL_SHA",           "ECDHE-RSA-NULL-SHA");
673        add("SSL_DH_anon_WITH_RC4_128_MD5",          "ADH-RC4-MD5");
674        add("TLS_DH_anon_WITH_AES_128_CBC_SHA",      "ADH-AES128-SHA");
675        add("TLS_DH_anon_WITH_AES_256_CBC_SHA",      "ADH-AES256-SHA");
676        add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",     "ADH-DES-CBC3-SHA");
677        add("SSL_DH_anon_WITH_DES_CBC_SHA",          "ADH-DES-CBC-SHA");
678        add("TLS_ECDH_anon_WITH_RC4_128_SHA",        "AECDH-RC4-SHA");
679        add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",    "AECDH-AES128-SHA");
680        add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",    "AECDH-AES256-SHA");
681        add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",   "AECDH-DES-CBC3-SHA");
682        add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",    "EXP-ADH-RC4-MD5");
683        add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", "EXP-ADH-DES-CBC-SHA");
684        add("TLS_ECDH_anon_WITH_NULL_SHA",           "AECDH-NULL-SHA");
685
686        // TLSv1.2 cipher suites
687        add("TLS_RSA_WITH_NULL_SHA256",                "NULL-SHA256");
688        add("TLS_RSA_WITH_AES_128_CBC_SHA256",         "AES128-SHA256");
689        add("TLS_RSA_WITH_AES_256_CBC_SHA256",         "AES256-SHA256");
690        add("TLS_RSA_WITH_AES_128_GCM_SHA256",         "AES128-GCM-SHA256");
691        add("TLS_RSA_WITH_AES_256_GCM_SHA384",         "AES256-GCM-SHA384");
692        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",     "DHE-RSA-AES128-SHA256");
693        add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",     "DHE-RSA-AES256-SHA256");
694        add("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",     "DHE-RSA-AES128-GCM-SHA256");
695        add("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",     "DHE-RSA-AES256-GCM-SHA384");
696        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",     "DHE-DSS-AES128-SHA256");
697        add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",     "DHE-DSS-AES256-SHA256");
698        add("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256",     "DHE-DSS-AES128-GCM-SHA256");
699        add("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384",     "DHE-DSS-AES256-GCM-SHA384");
700        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",    "ECDH-RSA-AES128-SHA256");
701        add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",    "ECDH-RSA-AES256-SHA384");
702        add("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",    "ECDH-RSA-AES128-GCM-SHA256");
703        add("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",    "ECDH-RSA-AES256-GCM-SHA384");
704        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",  "ECDH-ECDSA-AES128-SHA256");
705        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",  "ECDH-ECDSA-AES256-SHA384");
706        add("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",  "ECDH-ECDSA-AES128-GCM-SHA256");
707        add("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",  "ECDH-ECDSA-AES256-GCM-SHA384");
708        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",   "ECDHE-RSA-AES128-SHA256");
709        add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",   "ECDHE-RSA-AES256-SHA384");
710        add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",   "ECDHE-RSA-AES128-GCM-SHA256");
711        add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",   "ECDHE-RSA-AES256-GCM-SHA384");
712        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "ECDHE-ECDSA-AES128-SHA256");
713        add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "ECDHE-ECDSA-AES256-SHA384");
714        add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "ECDHE-ECDSA-AES128-GCM-SHA256");
715        add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "ECDHE-ECDSA-AES256-GCM-SHA384");
716        add("TLS_DH_anon_WITH_AES_128_CBC_SHA256",     "ADH-AES128-SHA256");
717        add("TLS_DH_anon_WITH_AES_256_CBC_SHA256",     "ADH-AES256-SHA256");
718        add("TLS_DH_anon_WITH_AES_128_GCM_SHA256",     "ADH-AES128-GCM-SHA256");
719        add("TLS_DH_anon_WITH_AES_256_GCM_SHA384",     "ADH-AES256-GCM-SHA384");
720
721        // No Kerberos in Android
722        // add("TLS_KRB5_WITH_RC4_128_SHA",           "KRB5-RC4-SHA");
723        // add("TLS_KRB5_WITH_RC4_128_MD5",           "KRB5-RC4-MD5");
724        // add("TLS_KRB5_WITH_3DES_EDE_CBC_SHA",      "KRB5-DES-CBC3-SHA");
725        // add("TLS_KRB5_WITH_3DES_EDE_CBC_MD5",      "KRB5-DES-CBC3-MD5");
726        // add("TLS_KRB5_WITH_DES_CBC_SHA",           "KRB5-DES-CBC-SHA");
727        // add("TLS_KRB5_WITH_DES_CBC_MD5",           "KRB5-DES-CBC-MD5");
728        // add("TLS_KRB5_EXPORT_WITH_RC4_40_SHA",     "EXP-KRB5-RC4-SHA");
729        // add("TLS_KRB5_EXPORT_WITH_RC4_40_MD5",     "EXP-KRB5-RC4-MD5");
730        // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", "EXP-KRB5-DES-CBC-SHA");
731        // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", "EXP-KRB5-DES-CBC-MD5");
732
733        // not implemented by either RI or OpenSSL
734        // add("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", null);
735        // add("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", null);
736
737        // EXPORT1024 suites were never standardized but were widely implemented.
738        // OpenSSL 0.9.8c and later have disabled TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES
739        // add("SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA", "EXP1024-DES-CBC-SHA");
740        // add("SSL_RSA_EXPORT1024_WITH_RC4_56_SHA",  "EXP1024-RC4-SHA");
741
742        // No RC2
743        // add("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5",  "EXP-RC2-CBC-MD5");
744        // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", "EXP-KRB5-RC2-CBC-SHA");
745        // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", "EXP-KRB5-RC2-CBC-MD5");
746
747        // Pre-Shared Key (PSK) cipher suites
748        add("TLS_PSK_WITH_3DES_EDE_CBC_SHA", "PSK-3DES-EDE-CBC-SHA");
749        add("TLS_PSK_WITH_AES_128_CBC_SHA", "PSK-AES128-CBC-SHA");
750        add("TLS_PSK_WITH_AES_256_CBC_SHA", "PSK-AES256-CBC-SHA");
751        add("TLS_PSK_WITH_RC4_128_SHA", "PSK-RC4-SHA");
752        add("TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", "ECDHE-PSK-WITH-AES-128-CBC-SHA256");
753        add("TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", "ECDHE-PSK-WITH-AES-256-CBC-SHA384");
754
755        // Signaling Cipher Suite Value for secure renegotiation handled as special case.
756        // add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", null);
757    }
758
759    private static final String[] SUPPORTED_CIPHER_SUITES;
760    static {
761        int size = STANDARD_TO_OPENSSL_CIPHER_SUITES.size();
762        SUPPORTED_CIPHER_SUITES = new String[size + 1];
763        STANDARD_TO_OPENSSL_CIPHER_SUITES.keySet().toArray(SUPPORTED_CIPHER_SUITES);
764        SUPPORTED_CIPHER_SUITES[size] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
765    }
766
767    // EVP_PKEY types from evp.h and objects.h
768    public static final int EVP_PKEY_RSA  = 6;   // NID_rsaEcnryption
769    public static final int EVP_PKEY_DSA  = 116; // NID_dsa
770    public static final int EVP_PKEY_DH   = 28;  // NID_dhKeyAgreement
771    public static final int EVP_PKEY_EC   = 408; // NID_X9_62_id_ecPublicKey
772    public static final int EVP_PKEY_HMAC = 855; // NID_hmac
773    public static final int EVP_PKEY_CMAC = 894; // NID_cmac
774
775    // RSA padding modes from rsa.h
776    public static final int RSA_PKCS1_PADDING = 1;
777    public static final int RSA_NO_PADDING    = 3;
778
779    // SSL mode from ssl.h
780    public static final long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000080L;
781    public static final long SSL_MODE_CBC_RECORD_SPLITTING = 0x00000100L;
782
783    // SSL options from ssl.h
784    public static final long SSL_OP_NO_TICKET                              = 0x00004000L;
785    public static final long SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 0x00010000L;
786    public static final long SSL_OP_NO_SSLv3                               = 0x02000000L;
787    public static final long SSL_OP_NO_TLSv1                               = 0x04000000L;
788    public static final long SSL_OP_NO_TLSv1_1                             = 0x10000000L;
789    public static final long SSL_OP_NO_TLSv1_2                             = 0x08000000L;
790
791    /*
792     * Client certificate types as defined in
793     * TLS 1.0 spec., 7.4.4. Certificate request.
794     * EC constants from RFC 4492.
795     * OpenSSL constants from ssl/tls1.h.
796     */
797    public static final byte TLS_CT_RSA_SIGN = 1;
798    public static final byte TLS_CT_DSS_SIGN = 2;
799    public static final byte TLS_CT_RSA_FIXED_DH = 3;
800    public static final byte TLS_CT_DSS_FIXED_DH = 4;
801    public static final byte TLS_CT_ECDSA_SIGN = 64;
802    public static final byte TLS_CT_RSA_FIXED_ECDH = 65;
803    public static final byte TLS_CT_ECDSA_FIXED_ECDH = 66;
804
805    /*
806     * Used in the SSL_get_shutdown and SSL_set_shutdown functions.
807     */
808    public static final int SSL_SENT_SHUTDOWN = 1;
809    public static final int SSL_RECEIVED_SHUTDOWN = 2;
810
811    public static native long SSL_CTX_new();
812
813    public static String[] getDefaultCipherSuites() {
814        // The default list of cipher suites is a trade-off between what we'd like to use and what
815        // servers currently support. We strive to be secure enough by default. We thus avoid
816        // unacceptably weak suites (e.g., those with bulk cipher secret key shorter than 128 bits),
817        // while maintaining the capability to connect to the majority of servers.
818        //
819        // Cipher suites are listed in preference order (favorite choice first) of the client.
820        // However, servers are not required to honor the order. The key rules governing the
821        // preference order are:
822        // * Prefer Forward Secrecy (i.e., cipher suites that use ECDHE and DHE for key agreement).
823        // * Prefer AES-GCM to AES-CBC whose MAC-pad-then-encrypt approach leads to weaknesses
824        //   (e.g., Lucky 13).
825        // * Prefer AES to RC4 whose foundations are a bit shaky. See
826        //   http://www.isg.rhul.ac.uk/tls/. BEAST and Lucky13 mitigations are enabled.
827        // * Prefer 128-bit bulk encryption to 256-bit one, because 128-bit is safe enough while
828        //   consuming less CPU/time/energy.
829        //
830        // NOTE: Removing cipher suites from this list needs to be done with caution, because this
831        // may prevent apps from connecting to servers they were previously able to connect to.
832        return new String[] {
833            "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
834            "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
835            "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
836            "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
837            "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
838            "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
839            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
840            "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
841            "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
842            "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
843            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
844            "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
845            "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
846            "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
847            "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
848            "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
849            "TLS_RSA_WITH_AES_128_GCM_SHA256",
850            "TLS_RSA_WITH_AES_256_GCM_SHA384",
851            "TLS_RSA_WITH_AES_128_CBC_SHA",
852            "TLS_RSA_WITH_AES_256_CBC_SHA",
853            "SSL_RSA_WITH_RC4_128_SHA",
854            TLS_EMPTY_RENEGOTIATION_INFO_SCSV
855        };
856    }
857
858    public static String[] getSupportedCipherSuites() {
859        return SUPPORTED_CIPHER_SUITES.clone();
860    }
861
862    public static native void SSL_CTX_free(long ssl_ctx);
863
864    public static native void SSL_CTX_set_session_id_context(long ssl_ctx, byte[] sid_ctx);
865
866    public static native long SSL_new(long ssl_ctx) throws SSLException;
867
868    public static native void SSL_enable_tls_channel_id(long ssl) throws SSLException;
869
870    public static native byte[] SSL_get_tls_channel_id(long ssl) throws SSLException;
871
872    public static native void SSL_set1_tls_channel_id(long ssl, long pkey);
873
874    public static native void SSL_use_certificate(long ssl, long[] x509refs);
875
876    public static native void SSL_use_PrivateKey(long ssl, long pkey);
877
878    public static native void SSL_check_private_key(long ssl) throws SSLException;
879
880    public static native void SSL_set_client_CA_list(long ssl, byte[][] asn1DerEncodedX500Principals);
881
882    public static native long SSL_get_mode(long ssl);
883
884    public static native long SSL_set_mode(long ssl, long mode);
885
886    public static native long SSL_clear_mode(long ssl, long mode);
887
888    public static native long SSL_get_options(long ssl);
889
890    public static native long SSL_set_options(long ssl, long options);
891
892    public static native long SSL_clear_options(long ssl, long options);
893
894    public static native void SSL_use_psk_identity_hint(long ssl, String identityHint)
895            throws SSLException;
896
897    public static native void set_SSL_psk_client_callback_enabled(long ssl, boolean enabled);
898
899    public static native void set_SSL_psk_server_callback_enabled(long ssl, boolean enabled);
900
901    public static String[] getDefaultProtocols() {
902        return new String[] { SUPPORTED_PROTOCOL_SSLV3,
903                              SUPPORTED_PROTOCOL_TLSV1,
904                              SUPPORTED_PROTOCOL_TLSV1_1,
905                              SUPPORTED_PROTOCOL_TLSV1_2,
906        };
907    }
908
909    public static String[] getSupportedProtocols() {
910        return new String[] { SUPPORTED_PROTOCOL_SSLV3,
911                              SUPPORTED_PROTOCOL_TLSV1,
912                              SUPPORTED_PROTOCOL_TLSV1_1,
913                              SUPPORTED_PROTOCOL_TLSV1_2,
914        };
915    }
916
917    public static void setEnabledProtocols(long ssl, String[] protocols) {
918        checkEnabledProtocols(protocols);
919        // openssl uses negative logic letting you disable protocols.
920        // so first, assume we need to set all (disable all) and clear none (enable none).
921        // in the loop, selectively move bits from set to clear (from disable to enable)
922        long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
923        long optionsToClear = 0;
924        for (int i = 0; i < protocols.length; i++) {
925            String protocol = protocols[i];
926            if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
927                optionsToSet &= ~SSL_OP_NO_SSLv3;
928                optionsToClear |= SSL_OP_NO_SSLv3;
929            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
930                optionsToSet &= ~SSL_OP_NO_TLSv1;
931                optionsToClear |= SSL_OP_NO_TLSv1;
932            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
933                optionsToSet &= ~SSL_OP_NO_TLSv1_1;
934                optionsToClear |= SSL_OP_NO_TLSv1_1;
935            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
936                optionsToSet &= ~SSL_OP_NO_TLSv1_2;
937                optionsToClear |= SSL_OP_NO_TLSv1_2;
938            } else {
939                // error checked by checkEnabledProtocols
940                throw new IllegalStateException();
941            }
942        }
943
944        SSL_set_options(ssl, optionsToSet);
945        SSL_clear_options(ssl, optionsToClear);
946    }
947
948    public static String[] checkEnabledProtocols(String[] protocols) {
949        if (protocols == null) {
950            throw new IllegalArgumentException("protocols == null");
951        }
952        for (int i = 0; i < protocols.length; i++) {
953            String protocol = protocols[i];
954            if (protocol == null) {
955                throw new IllegalArgumentException("protocols[" + i + "] == null");
956            }
957            if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
958                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))
959                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1))
960                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2))) {
961                throw new IllegalArgumentException("protocol " + protocol
962                                                   + " is not supported");
963            }
964        }
965        return protocols;
966    }
967
968    public static native void SSL_set_cipher_lists(long ssl, String[] ciphers);
969
970    /**
971     * Gets the list of cipher suites enabled for the provided {@code SSL} instance.
972     *
973     * @return array of {@code SSL_CIPHER} references.
974     */
975    public static native long[] SSL_get_ciphers(long ssl);
976
977    /*
978     * Constants for SSL_CIPHER algorithm_mkey (key exchange algorithm).
979     * OpenSSL constants from ssl/ssl_locl.h.
980     */
981    /** RSA key exchange */
982    public static final int SSL_kRSA =   0x00000001;
983    /** DH cert, RSA CA cert -- no such ciphersuite supported! */
984    public static final int SSL_kDHr =   0x00000002;
985    /** DH cert, DSA CA cert -- no such ciphersuite supported! */
986    public static final int SSL_kDHd =   0x00000004;
987    /** tmp DH key no DH cert */
988    public static final int SSL_kEDH =   0x00000008;
989    /** Kerberos5 key exchange */
990    public static final int SSL_kKRB5 =  0x00000010;
991    /** ECDH cert, RSA CA cert */
992    public static final int SSL_kECDHr = 0x00000020;
993    /** ECDH cert, ECDSA CA cert */
994    public static final int SSL_kECDHe = 0x00000040;
995    /** ephemeral ECDH */
996    public static final int SSL_kEECDH = 0x00000080;
997    /** PSK */
998    public static final int SSL_kPSK =   0x00000100;
999    /** GOST key exchange */
1000    public static final int SSL_kGOST =  0x00000200;
1001    /** SRP */
1002    public static final int SSL_kSRP =   0x00000400;
1003
1004    /*
1005     * Constants for SSL_CIPHER algorithm_auth (server authentication).
1006     * OpenSSL constants from ssl/ssl_locl.h.
1007     */
1008    /** RSA auth */
1009    public static final int SSL_aRSA =    0x00000001;
1010    /** DSS auth */
1011    public static final int SSL_aDSS =    0x00000002;
1012    /** no auth (i.e. use ADH or AECDH) */
1013    public static final int SSL_aNULL =   0x00000004;
1014    /** Fixed DH auth (kDHd or kDHr) -- no such ciphersuites supported! */
1015    public static final int SSL_aDH =     0x00000008;
1016    /** Fixed ECDH auth (kECDHe or kECDHr) */
1017    public static final int SSL_aECDH =   0x00000010;
1018    /** KRB5 auth */
1019    public static final int SSL_aKRB5 =   0x00000020;
1020    /** ECDSA auth*/
1021    public static final int SSL_aECDSA =  0x00000040;
1022    /** PSK auth */
1023    public static final int SSL_aPSK =    0x00000080;
1024    /** GOST R 34.10-94 signature auth */
1025    public static final int SSL_aGOST94 = 0x00000100;
1026    /** GOST R 34.10-2001 signature auth */
1027    public static final int SSL_aGOST01 = 0x00000200;
1028
1029    public static native int get_SSL_CIPHER_algorithm_mkey(long sslCipher);
1030    public static native int get_SSL_CIPHER_algorithm_auth(long sslCipher);
1031
1032    public static void setEnabledCipherSuites(long ssl, String[] cipherSuites) {
1033        checkEnabledCipherSuites(cipherSuites);
1034        List<String> opensslSuites = new ArrayList<String>();
1035        for (int i = 0; i < cipherSuites.length; i++) {
1036            String cipherSuite = cipherSuites[i];
1037            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
1038                continue;
1039            }
1040            String openssl = STANDARD_TO_OPENSSL_CIPHER_SUITES.get(cipherSuite);
1041            String cs = (openssl == null) ? cipherSuite : openssl;
1042            opensslSuites.add(cs);
1043        }
1044        SSL_set_cipher_lists(ssl, opensslSuites.toArray(new String[opensslSuites.size()]));
1045    }
1046
1047    public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
1048        if (cipherSuites == null) {
1049            throw new IllegalArgumentException("cipherSuites == null");
1050        }
1051        // makes sure all suites are valid, throwing on error
1052        for (int i = 0; i < cipherSuites.length; i++) {
1053            String cipherSuite = cipherSuites[i];
1054            if (cipherSuite == null) {
1055                throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
1056            }
1057            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
1058                continue;
1059            }
1060            if (STANDARD_TO_OPENSSL_CIPHER_SUITES.containsKey(cipherSuite)) {
1061                continue;
1062            }
1063            if (OPENSSL_TO_STANDARD_CIPHER_SUITES.containsKey(cipherSuite)) {
1064                // TODO log warning about using backward compatability
1065                continue;
1066            }
1067            throw new IllegalArgumentException("cipherSuite " + cipherSuite + " is not supported.");
1068        }
1069        return cipherSuites;
1070    }
1071
1072    /*
1073     * See the OpenSSL ssl.h header file for more information.
1074     */
1075    public static final int SSL_VERIFY_NONE =                 0x00;
1076    public static final int SSL_VERIFY_PEER =                 0x01;
1077    public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
1078
1079    public static native void SSL_set_accept_state(long sslNativePointer);
1080
1081    public static native void SSL_set_connect_state(long sslNativePointer);
1082
1083    public static native void SSL_set_verify(long sslNativePointer, int mode);
1084
1085    public static native void SSL_set_session(long sslNativePointer, long sslSessionNativePointer)
1086        throws SSLException;
1087
1088    public static native void SSL_set_session_creation_enabled(
1089            long sslNativePointer, boolean creationEnabled) throws SSLException;
1090
1091    public static native void SSL_set_tlsext_host_name(long sslNativePointer, String hostname)
1092            throws SSLException;
1093    public static native String SSL_get_servername(long sslNativePointer);
1094
1095    /**
1096     * Enables NPN for all SSL connections in the context.
1097     *
1098     * <p>For clients this causes the NPN extension to be included in the
1099     * ClientHello message.
1100     *
1101     * <p>For servers this causes the NPN extension to be included in the
1102     * ServerHello message. The NPN extension will not be included in the
1103     * ServerHello response if the client didn't include it in the ClientHello
1104     * request.
1105     *
1106     * <p>In either case the caller should pass a non-null byte array of NPN
1107     * protocols to {@link #SSL_do_handshake}.
1108     */
1109    public static native void SSL_CTX_enable_npn(long sslCtxNativePointer);
1110
1111    /**
1112     * Disables NPN for all SSL connections in the context.
1113     */
1114    public static native void SSL_CTX_disable_npn(long sslCtxNativePointer);
1115
1116    /**
1117     * For clients, sets the list of supported ALPN protocols in wire-format
1118     * (length-prefixed 8-bit strings).
1119     */
1120    public static native int SSL_set_alpn_protos(long sslPointer, byte[] protos);
1121
1122    /**
1123     * Returns the selected ALPN protocol. If the server did not select a
1124     * protocol, {@code null} will be returned.
1125     */
1126    public static native byte[] SSL_get0_alpn_selected(long sslPointer);
1127
1128    /**
1129     * Returns the sslSessionNativePointer of the negotiated session. If this is
1130     * a server negotiation, supplying the {@code alpnProtocols} will enable
1131     * ALPN negotiation.
1132     */
1133    public static native long SSL_do_handshake(long sslNativePointer,
1134                                               FileDescriptor fd,
1135                                               SSLHandshakeCallbacks shc,
1136                                               int timeoutMillis,
1137                                               boolean client_mode,
1138                                               byte[] npnProtocols,
1139                                               byte[] alpnProtocols)
1140        throws SSLException, SocketTimeoutException, CertificateException;
1141
1142    /**
1143     * Returns the sslSessionNativePointer of the negotiated session. If this is
1144     * a server negotiation, supplying the {@code alpnProtocols} will enable
1145     * ALPN negotiation.
1146     */
1147    public static native long SSL_do_handshake_bio(long sslNativePointer,
1148                                                   long sourceBioRef,
1149                                                   long sinkBioRef,
1150                                                   SSLHandshakeCallbacks shc,
1151                                                   boolean client_mode,
1152                                                   byte[] npnProtocols,
1153                                                   byte[] alpnProtocols)
1154        throws SSLException, SocketTimeoutException, CertificateException;
1155
1156    public static native byte[] SSL_get_npn_negotiated_protocol(long sslNativePointer);
1157
1158    /**
1159     * Currently only intended for forcing renegotiation for testing.
1160     * Not used within OpenSSLSocketImpl.
1161     */
1162    public static native void SSL_renegotiate(long sslNativePointer) throws SSLException;
1163
1164    /**
1165     * Returns the local X509 certificate references. Must X509_free when done.
1166     */
1167    public static native long[] SSL_get_certificate(long sslNativePointer);
1168
1169    /**
1170     * Returns the peer X509 certificate references. Must X509_free when done.
1171     */
1172    public static native long[] SSL_get_peer_cert_chain(long sslNativePointer);
1173
1174    /**
1175     * Reads with the native SSL_read function from the encrypted data stream
1176     * @return -1 if error or the end of the stream is reached.
1177     */
1178    public static native int SSL_read(long sslNativePointer,
1179                                      FileDescriptor fd,
1180                                      SSLHandshakeCallbacks shc,
1181                                      byte[] b, int off, int len, int readTimeoutMillis)
1182        throws IOException;
1183
1184    public static native int SSL_read_BIO(long sslNativePointer,
1185                                          byte[] dest,
1186                                          long sourceBioRef,
1187                                          long sinkBioRef,
1188                                          SSLHandshakeCallbacks shc)
1189        throws IOException;
1190
1191    /**
1192     * Writes with the native SSL_write function to the encrypted data stream.
1193     */
1194    public static native void SSL_write(long sslNativePointer,
1195                                        FileDescriptor fd,
1196                                        SSLHandshakeCallbacks shc,
1197                                        byte[] b, int off, int len, int writeTimeoutMillis)
1198        throws IOException;
1199
1200    public static native int SSL_write_BIO(long sslNativePointer,
1201                                           byte[] source,
1202                                           int length,
1203                                           long sinkBioRef,
1204                                           SSLHandshakeCallbacks shc)
1205        throws IOException;
1206
1207    public static native void SSL_interrupt(long sslNativePointer);
1208    public static native void SSL_shutdown(long sslNativePointer,
1209                                           FileDescriptor fd,
1210                                           SSLHandshakeCallbacks shc) throws IOException;
1211
1212    public static native void SSL_shutdown_BIO(long sslNativePointer,
1213                                               long sourceBioRef, long sinkBioRef,
1214                                               SSLHandshakeCallbacks shc) throws IOException;
1215
1216    public static native int SSL_get_shutdown(long sslNativePointer);
1217
1218    public static native void SSL_free(long sslNativePointer);
1219
1220    public static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
1221
1222    public static native long SSL_SESSION_get_time(long sslSessionNativePointer);
1223
1224    public static native String SSL_SESSION_get_version(long sslSessionNativePointer);
1225
1226    public static native String SSL_SESSION_cipher(long sslSessionNativePointer);
1227
1228    public static native void SSL_SESSION_free(long sslSessionNativePointer);
1229
1230    public static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
1231
1232    public static native long d2i_SSL_SESSION(byte[] data);
1233
1234    /**
1235     * A collection of callbacks from the native OpenSSL code that are
1236     * related to the SSL handshake initiated by SSL_do_handshake.
1237     */
1238    public interface SSLHandshakeCallbacks {
1239        /**
1240         * Verify that we trust the certificate chain is trusted.
1241         *
1242         * @param sslSessionNativePtr pointer to a reference of the SSL_SESSION
1243         * @param certificateChainRefs chain of X.509 certificate references
1244         * @param authMethod auth algorithm name
1245         *
1246         * @throws CertificateException if the certificate is untrusted
1247         */
1248        public void verifyCertificateChain(long sslSessionNativePtr, long[] certificateChainRefs,
1249                String authMethod) throws CertificateException;
1250
1251        /**
1252         * Called on an SSL client when the server requests (or
1253         * requires a certificate). The client can respond by using
1254         * SSL_use_certificate and SSL_use_PrivateKey to set a
1255         * certificate if has an appropriate one available, similar to
1256         * how the server provides its certificate.
1257         *
1258         * @param keyTypes key types supported by the server,
1259         * convertible to strings with #keyType
1260         * @param asn1DerEncodedX500Principals CAs known to the server
1261         */
1262        public void clientCertificateRequested(byte[] keyTypes,
1263                                               byte[][] asn1DerEncodedX500Principals)
1264            throws CertificateEncodingException, SSLException;
1265
1266        /**
1267         * Gets the key to be used in client mode for this connection in Pre-Shared Key (PSK) key
1268         * exchange.
1269         *
1270         * @param identityHint PSK identity hint provided by the server or {@code null} if no hint
1271         *        provided.
1272         * @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)
1273         *        by this method. This identity will be provided to the server.
1274         * @param key buffer to be populated with key material by this method.
1275         *
1276         * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
1277         *         error occurred in which case the handshake will be aborted.
1278         */
1279        public int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);
1280
1281        /**
1282         * Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key
1283         * exchange.
1284         *
1285         * @param identityHint PSK identity hint provided by this server to the client or
1286         *        {@code null} if no hint was provided.
1287         * @param identity PSK identity provided by the client.
1288         * @param key buffer to be populated with key material by this method.
1289         *
1290         * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
1291         *         error occurred in which case the handshake will be aborted.
1292         */
1293        public int serverPSKKeyRequested(String identityHint, String identity, byte[] key);
1294
1295        /**
1296         * Called when SSL state changes. This could be handshake completion.
1297         */
1298        public void onSSLStateChange(long sslSessionNativePtr, int type, int val);
1299    }
1300
1301    // Values used in the SSLHandshakeCallbacks#onSSLStateChange as the {@code type}.
1302    public static final int SSL_ST_CONNECT = 0x1000;
1303    public static final int SSL_ST_ACCEPT = 0x2000;
1304    public static final int SSL_ST_MASK = 0x0FFF;
1305    public static final int SSL_ST_INIT = (SSL_ST_CONNECT | SSL_ST_ACCEPT);
1306    public static final int SSL_ST_BEFORE = 0x4000;
1307    public static final int SSL_ST_OK = 0x03;
1308    public static final int SSL_ST_RENEGOTIATE = (0x04 | SSL_ST_INIT);
1309
1310    public static final int SSL_CB_LOOP = 0x01;
1311    public static final int SSL_CB_EXIT = 0x02;
1312    public static final int SSL_CB_READ = 0x04;
1313    public static final int SSL_CB_WRITE = 0x08;
1314    public static final int SSL_CB_ALERT = 0x4000;
1315    public static final int SSL_CB_READ_ALERT = (SSL_CB_ALERT | SSL_CB_READ);
1316    public static final int SSL_CB_WRITE_ALERT = (SSL_CB_ALERT | SSL_CB_WRITE);
1317    public static final int SSL_CB_ACCEPT_LOOP = (SSL_ST_ACCEPT | SSL_CB_LOOP);
1318    public static final int SSL_CB_ACCEPT_EXIT = (SSL_ST_ACCEPT | SSL_CB_EXIT);
1319    public static final int SSL_CB_CONNECT_LOOP = (SSL_ST_CONNECT | SSL_CB_LOOP);
1320    public static final int SSL_CB_CONNECT_EXIT = (SSL_ST_CONNECT | SSL_CB_EXIT);
1321    public static final int SSL_CB_HANDSHAKE_START = 0x10;
1322    public static final int SSL_CB_HANDSHAKE_DONE = 0x20;
1323
1324    /*
1325     * From ssl/ssl3.h
1326     */
1327    public static final int SSL3_RT_HEADER_LENGTH = 5;
1328    public static final int SSL_RT_MAX_CIPHER_BLOCK_SIZE = 16;
1329    public static final int SSL3_RT_MAX_MD_SIZE = 64;
1330    public static final int SSL3_RT_MAX_PLAIN_LENGTH = 16384;
1331    public static final int SSL3_RT_MAX_ENCRYPTED_OVERHEAD = 256 + SSL3_RT_MAX_MD_SIZE;
1332    public static final int SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD = SSL_RT_MAX_CIPHER_BLOCK_SIZE
1333            + SSL3_RT_MAX_MD_SIZE;
1334    public static final int SSL3_RT_MAX_COMPRESSED_LENGTH = SSL3_RT_MAX_PLAIN_LENGTH;
1335    public static final int SSL3_RT_MAX_ENCRYPTED_LENGTH = SSL3_RT_MAX_ENCRYPTED_OVERHEAD
1336            + SSL3_RT_MAX_COMPRESSED_LENGTH;
1337    public static final int SSL3_RT_MAX_PACKET_SIZE = SSL3_RT_MAX_ENCRYPTED_LENGTH
1338            + SSL3_RT_HEADER_LENGTH;
1339
1340    public static native long ERR_peek_last_error();
1341}
1342