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.nio.Buffer;
24import java.security.InvalidKeyException;
25import java.security.MessageDigest;
26import java.security.NoSuchAlgorithmException;
27import java.security.PrivateKey;
28import java.security.SignatureException;
29import java.security.cert.CertificateEncodingException;
30import java.security.cert.CertificateException;
31import java.security.cert.CertificateParsingException;
32import java.util.ArrayList;
33import java.util.Calendar;
34import java.util.HashMap;
35import java.util.HashSet;
36import java.util.LinkedHashMap;
37import java.util.List;
38import java.util.Map;
39import java.util.Set;
40import javax.crypto.BadPaddingException;
41import javax.crypto.IllegalBlockSizeException;
42import javax.net.ssl.SSLException;
43import javax.security.auth.x500.X500Principal;
44
45/**
46 * Provides the Java side of our JNI glue for OpenSSL.
47 */
48public final class NativeCrypto {
49
50    public static final boolean isBoringSSL;
51
52    // --- OpenSSL library initialization --------------------------------------
53    static {
54        NativeCryptoJni.init();
55        isBoringSSL = clinit();
56    }
57
58    private native static boolean clinit();
59
60    // --- ENGINE functions ----------------------------------------------------
61    public static native void ENGINE_load_dynamic();
62
63    public static native long ENGINE_by_id(String id);
64
65    public static native int ENGINE_add(long e);
66
67    public static native int ENGINE_init(long e);
68
69    public static native int ENGINE_finish(long e);
70
71    public static native int ENGINE_free(long e);
72
73    public static native long ENGINE_load_private_key(long e, String key_id) throws InvalidKeyException;
74
75    public static native String ENGINE_get_id(long engineRef);
76
77    public static native int ENGINE_ctrl_cmd_string(long engineRef, String cmd, String arg,
78            int cmd_optional);
79
80    // --- DSA/RSA public/private key handling functions -----------------------
81
82    public static native long EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
83                                               byte[] pub_key, byte[] priv_key);
84
85    public static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
86            byte[] dmp1, byte[] dmq1, byte[] iqmp);
87
88    public static native int EVP_PKEY_size(NativeRef.EVP_PKEY pkey);
89
90    public static native int EVP_PKEY_type(NativeRef.EVP_PKEY pkey);
91
92    public static native String EVP_PKEY_print_public(NativeRef.EVP_PKEY pkeyRef);
93
94    public static native String EVP_PKEY_print_params(NativeRef.EVP_PKEY pkeyRef);
95
96    public static native void EVP_PKEY_free(long pkey);
97
98    public static native int EVP_PKEY_cmp(NativeRef.EVP_PKEY pkey1, NativeRef.EVP_PKEY pkey2);
99
100    public static native byte[] i2d_PKCS8_PRIV_KEY_INFO(NativeRef.EVP_PKEY pkey);
101
102    public static native long d2i_PKCS8_PRIV_KEY_INFO(byte[] data);
103
104    public static native byte[] i2d_PUBKEY(NativeRef.EVP_PKEY pkey);
105
106    public static native long d2i_PUBKEY(byte[] data);
107
108    public static native long PEM_read_bio_PUBKEY(long bioCtx);
109
110    public static native long PEM_read_bio_PrivateKey(long bioCtx);
111
112    public static native long getRSAPrivateKeyWrapper(PrivateKey key, byte[] modulus);
113
114    public static native long getECPrivateKeyWrapper(PrivateKey key,
115            NativeRef.EC_GROUP ecGroupRef);
116
117    public static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
118
119    public static native int RSA_size(NativeRef.EVP_PKEY pkey);
120
121    public static native int RSA_private_encrypt(int flen, byte[] from, byte[] to,
122            NativeRef.EVP_PKEY pkey, int padding);
123
124    public static native int RSA_public_decrypt(int flen, byte[] from, byte[] to,
125            NativeRef.EVP_PKEY pkey, int padding) throws BadPaddingException, SignatureException;
126
127    public static native int RSA_public_encrypt(int flen, byte[] from, byte[] to,
128            NativeRef.EVP_PKEY pkey, int padding);
129
130    public static native int RSA_private_decrypt(int flen, byte[] from, byte[] to,
131            NativeRef.EVP_PKEY pkey, int padding) throws BadPaddingException, SignatureException;
132
133    /**
134     * @return array of {n, e}
135     */
136    public static native byte[][] get_RSA_public_params(NativeRef.EVP_PKEY rsa);
137
138    /**
139     * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
140     */
141    public static native byte[][] get_RSA_private_params(NativeRef.EVP_PKEY rsa);
142
143    public static native byte[] i2d_RSAPublicKey(NativeRef.EVP_PKEY rsa);
144
145    public static native byte[] i2d_RSAPrivateKey(NativeRef.EVP_PKEY rsa);
146
147    // --- EC functions --------------------------
148
149    /**
150     * Used to request EC_GROUP_new_curve_GFp to EC_GROUP_new_curve
151     */
152    public static final int EC_CURVE_GFP = 1;
153
154    /**
155     * Used to request EC_GROUP_new_curve_GF2m to EC_GROUP_new_curve
156     */
157    public static final int EC_CURVE_GF2M = 2;
158
159    public static native long EVP_PKEY_new_EC_KEY(NativeRef.EC_GROUP groupRef,
160            NativeRef.EC_POINT pubkeyRef, byte[] privkey);
161
162    public static native long EC_GROUP_new_by_curve_name(String curveName);
163
164    public static native long EC_GROUP_new_arbitrary(byte[] p, byte[] a, byte[] b, byte[] x,
165                                                     byte[] y, byte[] order, int cofactor);
166
167    public static native void EC_GROUP_set_asn1_flag(NativeRef.EC_GROUP groupRef, int flag);
168
169    public static native void EC_GROUP_set_point_conversion_form(NativeRef.EC_GROUP groupRef,
170            int form);
171
172    public static native String EC_GROUP_get_curve_name(NativeRef.EC_GROUP groupRef);
173
174    public static native byte[][] EC_GROUP_get_curve(NativeRef.EC_GROUP groupRef);
175
176    public static native void EC_GROUP_clear_free(long groupRef);
177
178    public static native long EC_GROUP_get_generator(NativeRef.EC_GROUP groupRef);
179
180    public static native int get_EC_GROUP_type(NativeRef.EC_GROUP groupRef);
181
182    public static native byte[] EC_GROUP_get_order(NativeRef.EC_GROUP groupRef);
183
184    public static native int EC_GROUP_get_degree(NativeRef.EC_GROUP groupRef);
185
186    public static native byte[] EC_GROUP_get_cofactor(NativeRef.EC_GROUP groupRef);
187
188    public static native long EC_POINT_new(NativeRef.EC_GROUP groupRef);
189
190    public static native void EC_POINT_clear_free(long pointRef);
191
192    public static native byte[][] EC_POINT_get_affine_coordinates(NativeRef.EC_GROUP groupRef,
193            NativeRef.EC_POINT pointRef);
194
195    public static native void EC_POINT_set_affine_coordinates(NativeRef.EC_GROUP groupRef,
196            NativeRef.EC_POINT pointRef, byte[] x, byte[] y);
197
198    public static native long EC_KEY_generate_key(NativeRef.EC_GROUP groupRef);
199
200    public static native long EC_KEY_get1_group(NativeRef.EVP_PKEY pkeyRef);
201
202    public static native byte[] EC_KEY_get_private_key(NativeRef.EVP_PKEY keyRef);
203
204    public static native long EC_KEY_get_public_key(NativeRef.EVP_PKEY keyRef);
205
206    public static native void EC_KEY_set_nonce_from_hash(NativeRef.EVP_PKEY keyRef,
207            boolean enabled);
208
209    public static native int ECDH_compute_key(byte[] out, int outOffset,
210            NativeRef.EVP_PKEY publicKeyRef, NativeRef.EVP_PKEY privateKeyRef) throws
211            InvalidKeyException;
212
213    // --- Message digest functions --------------
214
215    // These return const references
216    public static native long EVP_get_digestbyname(String name);
217
218    public static native int EVP_MD_size(long evp_md_const);
219
220    public static native int EVP_MD_block_size(long evp_md_const);
221
222    // --- Message digest context functions --------------
223
224    public static native long EVP_MD_CTX_create();
225
226    public static native void EVP_MD_CTX_cleanup(NativeRef.EVP_MD_CTX ctx);
227
228    public static native void EVP_MD_CTX_destroy(long ctx);
229
230    public static native int EVP_MD_CTX_copy_ex(NativeRef.EVP_MD_CTX dst_ctx,
231            NativeRef.EVP_MD_CTX src_ctx);
232
233    // --- Digest handling functions -------------------------------------------
234
235    public static native int EVP_DigestInit_ex(NativeRef.EVP_MD_CTX ctx, long evp_md);
236
237    public static native void EVP_DigestUpdate(NativeRef.EVP_MD_CTX ctx,
238            byte[] buffer, int offset, int length);
239
240    public static native void EVP_DigestUpdateDirect(NativeRef.EVP_MD_CTX ctx,
241            long ptr, int length);
242
243    public static native int EVP_DigestFinal_ex(NativeRef.EVP_MD_CTX ctx, byte[] hash,
244            int offset);
245
246    // --- Signature handling functions ----------------------------------------
247
248    public static native long EVP_DigestSignInit(NativeRef.EVP_MD_CTX ctx,
249            long evpMdRef, NativeRef.EVP_PKEY key);
250
251    public static native long EVP_DigestVerifyInit(NativeRef.EVP_MD_CTX ctx,
252            long evpMdRef, NativeRef.EVP_PKEY key);
253
254    public static native void EVP_DigestSignUpdate(NativeRef.EVP_MD_CTX ctx,
255            byte[] buffer, int offset, int length);
256
257    public static native void EVP_DigestSignUpdateDirect(NativeRef.EVP_MD_CTX ctx,
258            long ptr, int length);
259
260    public static native void EVP_DigestVerifyUpdate(NativeRef.EVP_MD_CTX ctx,
261            byte[] buffer, int offset, int length);
262
263    public static native void EVP_DigestVerifyUpdateDirect(NativeRef.EVP_MD_CTX ctx,
264            long ptr, int length);
265
266    public static native byte[] EVP_DigestSignFinal(NativeRef.EVP_MD_CTX ctx);
267
268    public static native boolean EVP_DigestVerifyFinal(NativeRef.EVP_MD_CTX ctx,
269            byte[] signature, int offset, int length);
270
271    public static native void EVP_PKEY_CTX_set_rsa_padding(long ctx, int pad);
272
273    public static native void EVP_PKEY_CTX_set_rsa_pss_saltlen(long ctx, int len);
274
275    public static native void EVP_PKEY_CTX_set_rsa_mgf1_md(long ctx, long evpMdRef);
276
277    // --- Block ciphers -------------------------------------------------------
278
279    // These return const references
280    public static native long EVP_get_cipherbyname(String string);
281
282    public static native void EVP_CipherInit_ex(NativeRef.EVP_CIPHER_CTX ctx, long evpCipher,
283            byte[] key, byte[] iv, boolean encrypting);
284
285    public static native int EVP_CipherUpdate(NativeRef.EVP_CIPHER_CTX ctx, byte[] out,
286            int outOffset, byte[] in, int inOffset, int inLength);
287
288    public static native int EVP_CipherFinal_ex(NativeRef.EVP_CIPHER_CTX ctx, byte[] out,
289            int outOffset) throws BadPaddingException, IllegalBlockSizeException;
290
291    public static native int EVP_CIPHER_iv_length(long evpCipher);
292
293    public static native long EVP_CIPHER_CTX_new();
294
295    public static native int EVP_CIPHER_CTX_block_size(NativeRef.EVP_CIPHER_CTX ctx);
296
297    public static native int get_EVP_CIPHER_CTX_buf_len(NativeRef.EVP_CIPHER_CTX ctx);
298
299    public static native boolean get_EVP_CIPHER_CTX_final_used(NativeRef.EVP_CIPHER_CTX ctx);
300
301    public static native void EVP_CIPHER_CTX_set_padding(NativeRef.EVP_CIPHER_CTX ctx,
302            boolean enablePadding);
303
304    public static native void EVP_CIPHER_CTX_set_key_length(NativeRef.EVP_CIPHER_CTX ctx,
305            int keyBitSize);
306
307    public static native void EVP_CIPHER_CTX_free(long ctx);
308
309    // --- AEAD ----------------------------------------------------------------
310    public static native long EVP_aead_aes_128_gcm();
311
312    public static native long EVP_aead_aes_256_gcm();
313
314    public static native long EVP_AEAD_CTX_init(long evpAead, byte[] key, int tagLen);
315
316    public static native void EVP_AEAD_CTX_cleanup(long ctx);
317
318    public static native int EVP_AEAD_max_overhead(long evpAead);
319
320    public static native int EVP_AEAD_nonce_length(long evpAead);
321
322    public static native int EVP_AEAD_max_tag_len(long evpAead);
323
324    public static native int EVP_AEAD_CTX_seal(NativeRef.EVP_AEAD_CTX ctx, byte[] out,
325            int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
326            throws BadPaddingException;
327
328    public static native int EVP_AEAD_CTX_open(NativeRef.EVP_AEAD_CTX ctx, byte[] out,
329            int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
330            throws BadPaddingException;
331
332    // --- HMAC functions ------------------------------------------------------
333
334    public static native long HMAC_CTX_new();
335
336    public static native void HMAC_CTX_free(long ctx);
337
338    public static native void HMAC_Init_ex(NativeRef.HMAC_CTX ctx, byte[] key, long evp_md);
339
340    public static native void HMAC_Update(NativeRef.HMAC_CTX ctx, byte[] in, int inOffset, int inLength);
341
342    public static native void HMAC_UpdateDirect(NativeRef.HMAC_CTX ctx, long inPtr, int inLength);
343
344    public static native byte[] HMAC_Final(NativeRef.HMAC_CTX ctx);
345
346    // --- RAND seeding --------------------------------------------------------
347
348    public static final int RAND_SEED_LENGTH_IN_BYTES = 1024;
349
350    public static native void RAND_seed(byte[] seed);
351
352    public static native int RAND_load_file(String filename, long max_bytes);
353
354    public static native void RAND_bytes(byte[] output);
355
356    // --- ASN.1 objects -------------------------------------------------------
357
358    public static native int OBJ_txt2nid(String oid);
359
360    public static native String OBJ_txt2nid_longName(String oid);
361
362    public static native String OBJ_txt2nid_oid(String oid);
363
364    // --- X509_NAME -----------------------------------------------------------
365
366    public static int X509_NAME_hash(X500Principal principal) {
367        return X509_NAME_hash(principal, "SHA1");
368    }
369    public static int X509_NAME_hash_old(X500Principal principal) {
370        return X509_NAME_hash(principal, "MD5");
371    }
372    private static int X509_NAME_hash(X500Principal principal, String algorithm) {
373        try {
374            byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
375            int offset = 0;
376            return (((digest[offset++] & 0xff) <<  0) |
377                    ((digest[offset++] & 0xff) <<  8) |
378                    ((digest[offset++] & 0xff) << 16) |
379                    ((digest[offset  ] & 0xff) << 24));
380        } catch (NoSuchAlgorithmException e) {
381            throw new AssertionError(e);
382        }
383    }
384
385    public static native String X509_NAME_print_ex(long x509nameCtx, long flags);
386
387    // --- X509 ----------------------------------------------------------------
388
389    /** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
390    public static final int GN_STACK_SUBJECT_ALT_NAME = 1;
391
392    /**
393     * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
394     * extension.
395     */
396    public static final int GN_STACK_ISSUER_ALT_NAME = 2;
397
398    /**
399     * Used to request only non-critical types in get_X509*_ext_oids.
400     */
401    public static final int EXTENSION_TYPE_NON_CRITICAL = 0;
402
403    /**
404     * Used to request only critical types in get_X509*_ext_oids.
405     */
406    public static final int EXTENSION_TYPE_CRITICAL = 1;
407
408    public static native long d2i_X509_bio(long bioCtx);
409
410    public static native long d2i_X509(byte[] encoded);
411
412    public static native long PEM_read_bio_X509(long bioCtx);
413
414    public static native byte[] i2d_X509(long x509ctx);
415
416    /** Takes an X509 context not an X509_PUBKEY context. */
417    public static native byte[] i2d_X509_PUBKEY(long x509ctx);
418
419    public static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
420
421    public static native long[] ASN1_seq_unpack_X509_bio(long bioRef);
422
423    public static native void X509_free(long x509ctx);
424
425    public static native long X509_dup(long x509ctx);
426
427    public static native int X509_cmp(long x509ctx1, long x509ctx2);
428
429    public static native void X509_print_ex(long bioCtx, long x509ctx, long nmflag, long certflag);
430
431    public static native byte[] X509_get_issuer_name(long x509ctx);
432
433    public static native byte[] X509_get_subject_name(long x509ctx);
434
435    public static native String get_X509_sig_alg_oid(long x509ctx);
436
437    public static native byte[] get_X509_sig_alg_parameter(long x509ctx);
438
439    public static native boolean[] get_X509_issuerUID(long x509ctx);
440
441    public static native boolean[] get_X509_subjectUID(long x509ctx);
442
443    public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException;
444
445    public static native String get_X509_pubkey_oid(long x509ctx);
446
447    public static native byte[] X509_get_ext_oid(long x509ctx, String oid);
448
449    public static native String[] get_X509_ext_oids(long x509ctx, int critical);
450
451    public static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, int type)
452            throws CertificateParsingException;
453
454    public static native boolean[] get_X509_ex_kusage(long x509ctx);
455
456    public static native String[] get_X509_ex_xkusage(long x509ctx);
457
458    public static native int get_X509_ex_pathlen(long x509ctx);
459
460    public static native long X509_get_notBefore(long x509ctx);
461
462    public static native long X509_get_notAfter(long x509ctx);
463
464    public static native long X509_get_version(long x509ctx);
465
466    public static native byte[] X509_get_serialNumber(long x509ctx);
467
468    public static native void X509_verify(long x509ctx, NativeRef.EVP_PKEY pkeyCtx)
469            throws BadPaddingException;
470
471    public static native byte[] get_X509_cert_info_enc(long x509ctx);
472
473    public static native byte[] get_X509_signature(long x509ctx);
474
475    public static native int get_X509_ex_flags(long x509ctx);
476
477    public static native int X509_check_issued(long ctx, long ctx2);
478
479    // --- PKCS7 ---------------------------------------------------------------
480
481    /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
482    public static final int PKCS7_CERTS = 1;
483
484    /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
485    public static final int PKCS7_CRLS = 2;
486
487    /** Returns an array of X509 or X509_CRL pointers. */
488    public static native long[] d2i_PKCS7_bio(long bioCtx, int which);
489
490    /** Returns an array of X509 or X509_CRL pointers. */
491    public static native byte[] i2d_PKCS7(long[] certs);
492
493    /** Returns an array of X509 or X509_CRL pointers. */
494    public static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
495
496    // --- X509_CRL ------------------------------------------------------------
497
498    public static native long d2i_X509_CRL_bio(long bioCtx);
499
500    public static native long PEM_read_bio_X509_CRL(long bioCtx);
501
502    public static native byte[] i2d_X509_CRL(long x509CrlCtx);
503
504    public static native void X509_CRL_free(long x509CrlCtx);
505
506    public static native void X509_CRL_print(long bioCtx, long x509CrlCtx);
507
508    public static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx);
509
510    public static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx);
511
512    public static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx);
513
514    /** Returns X509_REVOKED reference that is not duplicated! */
515    public static native long X509_CRL_get0_by_cert(long x509CrlCtx, long x509Ctx);
516
517    /** Returns X509_REVOKED reference that is not duplicated! */
518    public static native long X509_CRL_get0_by_serial(long x509CrlCtx, byte[] serial);
519
520    /** Returns an array of X509_REVOKED that are owned by the caller. */
521    public static native long[] X509_CRL_get_REVOKED(long x509CrlCtx);
522
523    public static native String[] get_X509_CRL_ext_oids(long x509ctx, int critical);
524
525    public static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, String oid);
526
527    public static native void X509_delete_ext(long x509, String oid);
528
529    public static native long X509_CRL_get_version(long x509CrlCtx);
530
531    public static native long X509_CRL_get_ext(long x509CrlCtx, String oid);
532
533    public static native byte[] get_X509_CRL_signature(long x509ctx);
534
535    public static native void X509_CRL_verify(long x509CrlCtx, NativeRef.EVP_PKEY pkeyCtx);
536
537    public static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx);
538
539    public static native long X509_CRL_get_lastUpdate(long x509CrlCtx);
540
541    public static native long X509_CRL_get_nextUpdate(long x509CrlCtx);
542
543    // --- X509_REVOKED --------------------------------------------------------
544
545    public static native long X509_REVOKED_dup(long x509RevokedCtx);
546
547    public static native byte[] i2d_X509_REVOKED(long x509RevokedCtx);
548
549    public static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical);
550
551    public static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid);
552
553    public static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx);
554
555    public static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid);
556
557    /** Returns ASN1_TIME reference. */
558    public static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx);
559
560    public static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx);
561
562    // --- X509_EXTENSION ------------------------------------------------------
563
564    public static native int X509_supported_extension(long x509ExtensionRef);
565
566    // --- ASN1_TIME -----------------------------------------------------------
567
568    public static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal);
569
570    // --- BIO stream creation -------------------------------------------------
571
572    public static native long create_BIO_InputStream(OpenSSLBIOInputStream is, boolean isFinite);
573
574    public static native long create_BIO_OutputStream(OutputStream os);
575
576    public static native int BIO_read(long bioRef, byte[] buffer);
577
578    public static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
579            throws IOException;
580
581    public static native void BIO_free_all(long bioRef);
582
583    // --- SSL handling --------------------------------------------------------
584
585    private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
586    private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
587    private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
588    private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
589
590    // STANDARD_TO_OPENSSL_CIPHER_SUITES is a map from OpenSSL-style
591    // cipher-suite names to the standard name for the same (i.e. the name that
592    // is registered with IANA).
593    public static final Map<String, String> OPENSSL_TO_STANDARD_CIPHER_SUITES
594            = new HashMap<String, String>();
595
596    // STANDARD_TO_OPENSSL_CIPHER_SUITES is a map from "standard" cipher suite
597    // names (i.e. the names that are registered with IANA) to the
598    // OpenSSL-style name for the same.
599    public static final Map<String, String> STANDARD_TO_OPENSSL_CIPHER_SUITES
600            = new LinkedHashMap<String, String>();
601
602    // SUPPORTED_CIPHER_SUITES_SET contains all the cipher suites supported by
603    // OpenSSL, named using "standard" (as opposed to OpenSSL-style) names.
604    public static final Set<String> SUPPORTED_CIPHER_SUITES_SET = new HashSet<String>();
605
606    private static void add(String openssl, String standard) {
607        OPENSSL_TO_STANDARD_CIPHER_SUITES.put(openssl, standard);
608        STANDARD_TO_OPENSSL_CIPHER_SUITES.put(standard, openssl);
609    }
610
611    /**
612     * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
613     * indication signaling cipher suite value. It is not a real
614     * cipher suite. It is just an indication in the default and
615     * supported cipher suite lists indicates that the implementation
616     * supports secure renegotiation.
617     * <p>
618     * In the RI, its presence means that the SCSV is sent in the
619     * cipher suite list to indicate secure renegotiation support and
620     * its absense means to send an empty TLS renegotiation info
621     * extension instead.
622     * <p>
623     * However, OpenSSL doesn't provide an API to give this level of
624     * control, instead always sending the SCSV and always including
625     * the empty renegotiation info if TLS is used (as opposed to
626     * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
627     * be passed for compatibility as to provide the hint that we
628     * support secure renegotiation.
629     */
630    public static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV
631            = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
632
633    /**
634     * TLS_FALLBACK_SCSV is from
635     * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
636     * to indicate to the server that this is a fallback protocol
637     * request.
638     */
639    public static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV";
640
641    static {
642        add("ADH-AES128-GCM-SHA256",		"TLS_DH_anon_WITH_AES_128_GCM_SHA256");
643        add("ADH-AES128-SHA256",		"TLS_DH_anon_WITH_AES_128_CBC_SHA256");
644        add("ADH-AES128-SHA",			"TLS_DH_anon_WITH_AES_128_CBC_SHA");
645        add("ADH-AES256-GCM-SHA384",		"TLS_DH_anon_WITH_AES_256_GCM_SHA384");
646        add("ADH-AES256-SHA256",		"TLS_DH_anon_WITH_AES_256_CBC_SHA256");
647        add("ADH-AES256-SHA",			"TLS_DH_anon_WITH_AES_256_CBC_SHA");
648        add("ADH-DES-CBC3-SHA",			"SSL_DH_anon_WITH_3DES_EDE_CBC_SHA");
649        add("ADH-DES-CBC-SHA",			"SSL_DH_anon_WITH_DES_CBC_SHA");
650        add("ADH-RC4-MD5",			"SSL_DH_anon_WITH_RC4_128_MD5");
651        add("AECDH-AES128-SHA",			"TLS_ECDH_anon_WITH_AES_128_CBC_SHA");
652        add("AECDH-AES256-SHA",			"TLS_ECDH_anon_WITH_AES_256_CBC_SHA");
653        add("AECDH-DES-CBC3-SHA",		"TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA");
654        add("AECDH-NULL-SHA",			"TLS_ECDH_anon_WITH_NULL_SHA");
655        add("AECDH-RC4-SHA",			"TLS_ECDH_anon_WITH_RC4_128_SHA");
656        add("AES128-GCM-SHA256",		"TLS_RSA_WITH_AES_128_GCM_SHA256");
657        add("AES128-SHA256",			"TLS_RSA_WITH_AES_128_CBC_SHA256");
658        add("AES128-SHA",			"TLS_RSA_WITH_AES_128_CBC_SHA");
659        add("AES256-GCM-SHA384",		"TLS_RSA_WITH_AES_256_GCM_SHA384");
660        add("AES256-SHA256",			"TLS_RSA_WITH_AES_256_CBC_SHA256");
661        add("AES256-SHA",			"TLS_RSA_WITH_AES_256_CBC_SHA");
662        add("DES-CBC3-SHA",			"SSL_RSA_WITH_3DES_EDE_CBC_SHA");
663        add("DES-CBC-SHA",			"SSL_RSA_WITH_DES_CBC_SHA");
664        add("DHE-RSA-AES128-GCM-SHA256",	"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256");
665        add("DHE-RSA-AES128-SHA256",		"TLS_DHE_RSA_WITH_AES_128_CBC_SHA256");
666        add("DHE-RSA-AES128-SHA",		"TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
667        add("DHE-RSA-AES256-GCM-SHA384",	"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384");
668        add("DHE-RSA-AES256-SHA256",		"TLS_DHE_RSA_WITH_AES_256_CBC_SHA256");
669        add("DHE-RSA-AES256-SHA",		"TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
670        add("DHE-RSA-CHACHA20-POLY1305",	"TLS_DHE_RSA_WITH_CHACHA20_POLY1305");
671        add("ECDH-ECDSA-AES128-GCM-SHA256",    	"TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256");
672        add("ECDH-ECDSA-AES128-SHA256",		"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256");
673        add("ECDH-ECDSA-AES128-SHA",		"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA");
674        add("ECDH-ECDSA-AES256-GCM-SHA384",    	"TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384");
675        add("ECDH-ECDSA-AES256-SHA384",		"TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384");
676        add("ECDH-ECDSA-AES256-SHA",		"TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
677        add("ECDH-ECDSA-DES-CBC3-SHA",		"TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA");
678        add("ECDH-ECDSA-NULL-SHA",		"TLS_ECDH_ECDSA_WITH_NULL_SHA");
679        add("ECDH-ECDSA-RC4-SHA",		"TLS_ECDH_ECDSA_WITH_RC4_128_SHA");
680        add("ECDHE-ECDSA-AES128-GCM-SHA256",   	"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
681        add("ECDHE-ECDSA-AES128-SHA256",	"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256");
682        add("ECDHE-ECDSA-AES128-SHA",		"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
683        add("ECDHE-ECDSA-AES256-GCM-SHA384",   	"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
684        add("ECDHE-ECDSA-AES256-SHA384",	"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384");
685        add("ECDHE-ECDSA-AES256-SHA",		"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
686        add("ECDHE-ECDSA-CHACHA20-POLY1305",   	"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305");
687        add("ECDHE-ECDSA-CHACHA20-POLY1305",	"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256");
688        add("ECDHE-ECDSA-DES-CBC3-SHA",		"TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA");
689        add("ECDHE-ECDSA-NULL-SHA",		"TLS_ECDHE_ECDSA_WITH_NULL_SHA");
690        add("ECDHE-ECDSA-RC4-SHA",		"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA");
691        add("ECDHE-PSK-AES128-CBC-SHA",		"TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA");
692        add("ECDHE-PSK-AES128-GCM-SHA256",     	"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256");
693        add("ECDHE-PSK-AES256-CBC-SHA",		"TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA");
694        add("ECDHE-PSK-AES256-GCM-SHA384",     	"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384");
695        add("ECDHE-PSK-CHACHA20-POLY1305",	"TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256");
696        add("ECDHE-RSA-AES128-GCM-SHA256",     	"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
697        add("ECDHE-RSA-AES128-SHA256",		"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
698        add("ECDHE-RSA-AES128-SHA",		"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
699        add("ECDHE-RSA-AES256-GCM-SHA384",     	"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
700        add("ECDHE-RSA-AES256-SHA384",		"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384");
701        add("ECDHE-RSA-AES256-SHA",		"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
702        add("ECDHE-RSA-CHACHA20-POLY1305",     	"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305");
703        add("ECDHE-RSA-CHACHA20-POLY1305",	"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
704        add("ECDHE-RSA-DES-CBC3-SHA",		"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA");
705        add("ECDHE-RSA-NULL-SHA",		"TLS_ECDHE_RSA_WITH_NULL_SHA");
706        add("ECDHE-RSA-RC4-SHA",		"TLS_ECDHE_RSA_WITH_RC4_128_SHA");
707        add("ECDH-RSA-AES128-GCM-SHA256",      	"TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256");
708        add("ECDH-RSA-AES128-SHA256",		"TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256");
709        add("ECDH-RSA-AES128-SHA",		"TLS_ECDH_RSA_WITH_AES_128_CBC_SHA");
710        add("ECDH-RSA-AES256-GCM-SHA384",      	"TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384");
711        add("ECDH-RSA-AES256-SHA384",		"TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384");
712        add("ECDH-RSA-AES256-SHA",		"TLS_ECDH_RSA_WITH_AES_256_CBC_SHA");
713        add("ECDH-RSA-DES-CBC3-SHA",		"TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA");
714        add("ECDH-RSA-NULL-SHA",		"TLS_ECDH_RSA_WITH_NULL_SHA");
715        add("ECDH-RSA-RC4-SHA",			"TLS_ECDH_RSA_WITH_RC4_128_SHA");
716        add("EDH-RSA-DES-CBC3-SHA",		"SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
717        add("EDH-RSA-DES-CBC-SHA",		"SSL_DHE_RSA_WITH_DES_CBC_SHA");
718        add("EXP-ADH-DES-CBC-SHA",		"SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
719        add("EXP-ADH-RC4-MD5",			"SSL_DH_anon_EXPORT_WITH_RC4_40_MD5");
720        add("EXP-DES-CBC-SHA",			"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA");
721        add("EXP-EDH-RSA-DES-CBC-SHA",		"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
722        add("EXP-RC4-MD5",			"SSL_RSA_EXPORT_WITH_RC4_40_MD5");
723        add("NULL-MD5",				"SSL_RSA_WITH_NULL_MD5");
724        add("NULL-SHA256",			"TLS_RSA_WITH_NULL_SHA256");
725        add("NULL-SHA",				"SSL_RSA_WITH_NULL_SHA");
726        add("PSK-3DES-EDE-CBC-SHA",		"TLS_PSK_WITH_3DES_EDE_CBC_SHA");
727        add("PSK-AES128-CBC-SHA",		"TLS_PSK_WITH_AES_128_CBC_SHA");
728        add("PSK-AES256-CBC-SHA",		"TLS_PSK_WITH_AES_256_CBC_SHA");
729        add("PSK-RC4-SHA",			"TLS_PSK_WITH_RC4_128_SHA");
730        add("RC4-MD5",				"SSL_RSA_WITH_RC4_128_MD5");
731        add("RC4-SHA",				"SSL_RSA_WITH_RC4_128_SHA");
732
733        // Signaling Cipher Suite Value for secure renegotiation handled as special case.
734        // add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", null);
735
736        // Similarly, the fallback SCSV is handled as a special case.
737        // add("TLS_FALLBACK_SCSV", null);
738    }
739
740    private static final String[] SUPPORTED_CIPHER_SUITES;
741    static {
742        // Cipher selection string must work with OpenSSL and BoringSSL.
743        String[] allOpenSSLCipherSuites = get_cipher_names("ALL:-EXP:-SRP:-SEED:-CAMELLIA:-DSS:-RC2:-DES-CBC-MD5:-DES-CBC3-MD5");
744
745        int size = allOpenSSLCipherSuites.length;
746        SUPPORTED_CIPHER_SUITES = new String[size + 2];
747        for (int i = 0; i < size; i++) {
748            String standardName = OPENSSL_TO_STANDARD_CIPHER_SUITES.get(allOpenSSLCipherSuites[i]);
749            if (standardName == null) {
750                throw new IllegalArgumentException("Unknown cipher suite supported by native code: " +
751                                                   allOpenSSLCipherSuites[i]);
752            }
753            SUPPORTED_CIPHER_SUITES[i] = standardName;
754            SUPPORTED_CIPHER_SUITES_SET.add(standardName);
755        }
756        SUPPORTED_CIPHER_SUITES[size] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
757        SUPPORTED_CIPHER_SUITES[size + 1] = TLS_FALLBACK_SCSV;
758    }
759
760    /**
761     * Returns 1 if the BoringSSL believes the CPU has AES accelerated hardware
762     * instructions. Used to determine cipher suite ordering.
763     */
764    public static native int EVP_has_aes_hardware();
765
766    public static native long SSL_CTX_new();
767
768    // IMPLEMENTATION NOTE: The default list of cipher suites is a trade-off between what we'd like
769    // to use and what servers currently support. We strive to be secure enough by default. We thus
770    // avoid unacceptably weak suites (e.g., those with bulk cipher secret key shorter than 128
771    // bits), while maintaining the capability to connect to the majority of servers.
772    //
773    // Cipher suites are listed in preference order (favorite choice first) of the client. However,
774    // servers are not required to honor the order. The key rules governing the preference order
775    // are:
776    // * Prefer Forward Secrecy (i.e., cipher suites that use ECDHE and DHE for key agreement).
777    // * Prefer ChaCha20-Poly1305 to AES-GCM unless hardware support for AES is available.
778    // * Prefer AES-GCM to AES-CBC whose MAC-pad-then-encrypt approach leads to weaknesses (e.g.,
779    //   Lucky 13).
780    // * Prefer 128-bit bulk encryption to 256-bit one, because 128-bit is safe enough while
781    //   consuming less CPU/time/energy.
782    //
783    // NOTE: Removing cipher suites from this list needs to be done with caution, because this may
784    // prevent apps from connecting to servers they were previously able to connect to.
785
786    /** X.509 based cipher suites enabled by default (if requested), in preference order. */
787    static final String[] DEFAULT_X509_CIPHER_SUITES = EVP_has_aes_hardware() == 1 ?
788            new String[] {
789                    "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
790                    "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
791                    "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
792                    "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
793                    "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
794                    "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
795                    "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
796                    "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
797                    "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
798                    "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
799                    "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
800                    "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
801                    "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
802                    "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
803                    "TLS_RSA_WITH_AES_128_GCM_SHA256",
804                    "TLS_RSA_WITH_AES_256_GCM_SHA384",
805                    "TLS_RSA_WITH_AES_128_CBC_SHA",
806                    "TLS_RSA_WITH_AES_256_CBC_SHA",
807            } :
808            new String[] {
809                    "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
810                    "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
811                    "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
812                    "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
813                    "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
814                    "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
815                    "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
816                    "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
817                    "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
818                    "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
819                    "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
820                    "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
821                    "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
822                    "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
823                    "TLS_RSA_WITH_AES_128_GCM_SHA256",
824                    "TLS_RSA_WITH_AES_256_GCM_SHA384",
825                    "TLS_RSA_WITH_AES_128_CBC_SHA",
826                    "TLS_RSA_WITH_AES_256_CBC_SHA",
827            };
828
829    /** TLS-PSK cipher suites enabled by default (if requested), in preference order. */
830    static final String[] DEFAULT_PSK_CIPHER_SUITES = new String[] {
831        "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
832        "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
833        "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
834        "TLS_PSK_WITH_AES_128_CBC_SHA",
835        "TLS_PSK_WITH_AES_256_CBC_SHA",
836    };
837
838    public static String[] getSupportedCipherSuites() {
839        return SUPPORTED_CIPHER_SUITES.clone();
840    }
841
842    public static native void SSL_CTX_free(long ssl_ctx);
843
844    public static native void SSL_CTX_set_session_id_context(long ssl_ctx, byte[] sid_ctx);
845
846    public static native long SSL_new(long ssl_ctx) throws SSLException;
847
848    public static native void SSL_enable_tls_channel_id(long ssl) throws SSLException;
849
850    public static native byte[] SSL_get_tls_channel_id(long ssl) throws SSLException;
851
852    public static native void SSL_set1_tls_channel_id(long ssl, NativeRef.EVP_PKEY pkey);
853
854    public static native void SSL_use_certificate(long ssl, long[] x509refs);
855
856    public static native void SSL_use_PrivateKey(long ssl, NativeRef.EVP_PKEY pkey);
857
858    public static native void SSL_check_private_key(long ssl) throws SSLException;
859
860    public static native void SSL_set_client_CA_list(long ssl, byte[][] asn1DerEncodedX500Principals);
861
862    public static native long SSL_get_mode(long ssl);
863
864    public static native long SSL_set_mode(long ssl, long mode);
865
866    public static native long SSL_clear_mode(long ssl, long mode);
867
868    public static native long SSL_get_options(long ssl);
869
870    public static native long SSL_set_options(long ssl, long options);
871
872    public static native long SSL_clear_options(long ssl, long options);
873
874    public static native void SSL_enable_signed_cert_timestamps(long ssl);
875
876    public static native byte[] SSL_get_signed_cert_timestamp_list(long ssl);
877
878    public static native void SSL_CTX_set_signed_cert_timestamp_list(long ssl, byte[] list);
879
880    public static native void SSL_enable_ocsp_stapling(long ssl);
881
882    public static native byte[] SSL_get_ocsp_response(long ssl);
883
884    public static native void SSL_CTX_set_ocsp_response(long ssl, byte[] response);
885
886    public static native void SSL_use_psk_identity_hint(long ssl, String identityHint)
887            throws SSLException;
888
889    public static native void set_SSL_psk_client_callback_enabled(long ssl, boolean enabled);
890
891    public static native void set_SSL_psk_server_callback_enabled(long ssl, boolean enabled);
892
893    /** Protocols to enable by default when "TLSv1.2" is requested. */
894    public static final String[] TLSV12_PROTOCOLS = new String[] {
895        SUPPORTED_PROTOCOL_TLSV1,
896        SUPPORTED_PROTOCOL_TLSV1_1,
897        SUPPORTED_PROTOCOL_TLSV1_2,
898    };
899
900    /** Protocols to enable by default when "TLSv1.1" is requested. */
901    public static final String[] TLSV11_PROTOCOLS = new String[] {
902        SUPPORTED_PROTOCOL_TLSV1,
903        SUPPORTED_PROTOCOL_TLSV1_1,
904        SUPPORTED_PROTOCOL_TLSV1_2,
905    };
906
907    /** Protocols to enable by default when "TLSv1" is requested. */
908    public static final String[] TLSV1_PROTOCOLS  = new String[] {
909        SUPPORTED_PROTOCOL_TLSV1,
910        SUPPORTED_PROTOCOL_TLSV1_1,
911        SUPPORTED_PROTOCOL_TLSV1_2,
912    };
913
914    /** Protocols to enable by default when "SSLv3" is requested. */
915    public static final String[] SSLV3_PROTOCOLS  = new String[] {
916        SUPPORTED_PROTOCOL_SSLV3,
917        SUPPORTED_PROTOCOL_TLSV1,
918        SUPPORTED_PROTOCOL_TLSV1_1,
919        SUPPORTED_PROTOCOL_TLSV1_2,
920    };
921
922    public static final String[] DEFAULT_PROTOCOLS = TLSV12_PROTOCOLS;
923
924    public static String[] getSupportedProtocols() {
925        return new String[] { SUPPORTED_PROTOCOL_SSLV3,
926                              SUPPORTED_PROTOCOL_TLSV1,
927                              SUPPORTED_PROTOCOL_TLSV1_1,
928                              SUPPORTED_PROTOCOL_TLSV1_2,
929        };
930    }
931
932    public static void setEnabledProtocols(long ssl, String[] protocols) {
933        checkEnabledProtocols(protocols);
934        // openssl uses negative logic letting you disable protocols.
935        // so first, assume we need to set all (disable all) and clear none (enable none).
936        // in the loop, selectively move bits from set to clear (from disable to enable)
937        long optionsToSet = (NativeConstants.SSL_OP_NO_SSLv3 | NativeConstants.SSL_OP_NO_TLSv1 | NativeConstants.SSL_OP_NO_TLSv1_1 | NativeConstants.SSL_OP_NO_TLSv1_2);
938        long optionsToClear = 0;
939        for (int i = 0; i < protocols.length; i++) {
940            String protocol = protocols[i];
941            if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
942                optionsToSet &= ~NativeConstants.SSL_OP_NO_SSLv3;
943                optionsToClear |= NativeConstants.SSL_OP_NO_SSLv3;
944            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
945                optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1;
946                optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1;
947            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
948                optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1_1;
949                optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1_1;
950            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
951                optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1_2;
952                optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1_2;
953            } else {
954                // error checked by checkEnabledProtocols
955                throw new IllegalStateException();
956            }
957        }
958
959        SSL_set_options(ssl, optionsToSet);
960        SSL_clear_options(ssl, optionsToClear);
961    }
962
963    public static String[] checkEnabledProtocols(String[] protocols) {
964        if (protocols == null) {
965            throw new IllegalArgumentException("protocols == null");
966        }
967        for (int i = 0; i < protocols.length; i++) {
968            String protocol = protocols[i];
969            if (protocol == null) {
970                throw new IllegalArgumentException("protocols[" + i + "] == null");
971            }
972            if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
973                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))
974                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1))
975                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2))) {
976                throw new IllegalArgumentException("protocol " + protocol
977                                                   + " is not supported");
978            }
979        }
980        return protocols;
981    }
982
983    public static native void SSL_set_cipher_lists(long ssl, String[] ciphers);
984
985    /**
986     * Gets the list of cipher suites enabled for the provided {@code SSL} instance.
987     *
988     * @return array of {@code SSL_CIPHER} references.
989     */
990    public static native long[] SSL_get_ciphers(long ssl);
991
992    public static void setEnabledCipherSuites(long ssl, String[] cipherSuites) {
993        checkEnabledCipherSuites(cipherSuites);
994        List<String> opensslSuites = new ArrayList<String>();
995        for (int i = 0; i < cipherSuites.length; i++) {
996            String cipherSuite = cipherSuites[i];
997            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
998                continue;
999            }
1000            if (cipherSuite.equals(TLS_FALLBACK_SCSV)) {
1001                SSL_set_mode(ssl, NativeConstants.SSL_MODE_SEND_FALLBACK_SCSV);
1002                continue;
1003            }
1004            String openssl = STANDARD_TO_OPENSSL_CIPHER_SUITES.get(cipherSuite);
1005            String cs = (openssl == null) ? cipherSuite : openssl;
1006            opensslSuites.add(cs);
1007        }
1008        SSL_set_cipher_lists(ssl, opensslSuites.toArray(new String[opensslSuites.size()]));
1009    }
1010
1011    public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
1012        if (cipherSuites == null) {
1013            throw new IllegalArgumentException("cipherSuites == null");
1014        }
1015        // makes sure all suites are valid, throwing on error
1016        for (int i = 0; i < cipherSuites.length; i++) {
1017            String cipherSuite = cipherSuites[i];
1018            if (cipherSuite == null) {
1019                throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
1020            }
1021            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV) ||
1022                    cipherSuite.equals(TLS_FALLBACK_SCSV)) {
1023                continue;
1024            }
1025            if (SUPPORTED_CIPHER_SUITES_SET.contains(cipherSuite)) {
1026                continue;
1027            }
1028
1029            // For backwards compatibility, it's allowed for |cipherSuite| to
1030            // be an OpenSSL-style cipher-suite name.
1031            String standardName = OPENSSL_TO_STANDARD_CIPHER_SUITES.get(cipherSuite);
1032            if (standardName != null && SUPPORTED_CIPHER_SUITES_SET.contains(standardName)) {
1033                // TODO log warning about using backward compatability
1034                continue;
1035            }
1036            throw new IllegalArgumentException("cipherSuite " + cipherSuite + " is not supported.");
1037        }
1038        return cipherSuites;
1039    }
1040
1041    /*
1042     * See the OpenSSL ssl.h header file for more information.
1043     */
1044    public static final int SSL_VERIFY_NONE =                 0x00;
1045    public static final int SSL_VERIFY_PEER =                 0x01;
1046    public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
1047
1048    public static native void SSL_set_accept_state(long sslNativePointer);
1049
1050    public static native void SSL_set_connect_state(long sslNativePointer);
1051
1052    public static native void SSL_set_verify(long sslNativePointer, int mode);
1053
1054    public static native void SSL_set_session(long sslNativePointer, long sslSessionNativePointer)
1055        throws SSLException;
1056
1057    public static native void SSL_set_session_creation_enabled(
1058            long sslNativePointer, boolean creationEnabled) throws SSLException;
1059
1060    public static native boolean SSL_session_reused(long sslNativePointer);
1061
1062    public static native void SSL_set_reject_peer_renegotiations(
1063            long sslNativePointer, boolean renegotiationRejected) throws SSLException;
1064
1065    public static native void SSL_set_tlsext_host_name(long sslNativePointer, String hostname)
1066            throws SSLException;
1067    public static native String SSL_get_servername(long sslNativePointer);
1068
1069    /**
1070     * Enables NPN for all SSL connections in the context.
1071     *
1072     * <p>For clients this causes the NPN extension to be included in the
1073     * ClientHello message.
1074     *
1075     * <p>For servers this causes the NPN extension to be included in the
1076     * ServerHello message. The NPN extension will not be included in the
1077     * ServerHello response if the client didn't include it in the ClientHello
1078     * request.
1079     *
1080     * <p>In either case the caller should pass a non-null byte array of NPN
1081     * protocols to {@link #SSL_do_handshake}.
1082     */
1083    public static native void SSL_CTX_enable_npn(long sslCtxNativePointer);
1084
1085    /**
1086     * Disables NPN for all SSL connections in the context.
1087     */
1088    public static native void SSL_CTX_disable_npn(long sslCtxNativePointer);
1089
1090    /**
1091     * For clients, sets the list of supported ALPN protocols in wire-format
1092     * (length-prefixed 8-bit strings).
1093     */
1094    public static native int SSL_set_alpn_protos(long sslPointer, byte[] protos);
1095
1096    /**
1097     * Returns the selected ALPN protocol. If the server did not select a
1098     * protocol, {@code null} will be returned.
1099     */
1100    public static native byte[] SSL_get0_alpn_selected(long sslPointer);
1101
1102    /**
1103     * Returns the sslSessionNativePointer of the negotiated session. If this is
1104     * a server negotiation, supplying the {@code alpnProtocols} will enable
1105     * ALPN negotiation.
1106     */
1107    public static native long SSL_do_handshake(long sslNativePointer,
1108                                               FileDescriptor fd,
1109                                               SSLHandshakeCallbacks shc,
1110                                               int timeoutMillis,
1111                                               boolean client_mode,
1112                                               byte[] npnProtocols,
1113                                               byte[] alpnProtocols)
1114        throws SSLException, SocketTimeoutException, CertificateException;
1115
1116    /**
1117     * Returns the sslSessionNativePointer of the negotiated session. If this is
1118     * a server negotiation, supplying the {@code alpnProtocols} will enable
1119     * ALPN negotiation.
1120     */
1121    public static native long SSL_do_handshake_bio(long sslNativePointer,
1122                                                   long sourceBioRef,
1123                                                   long sinkBioRef,
1124                                                   SSLHandshakeCallbacks shc,
1125                                                   boolean client_mode,
1126                                                   byte[] npnProtocols,
1127                                                   byte[] alpnProtocols)
1128        throws SSLException, SocketTimeoutException, CertificateException;
1129
1130    public static native byte[] SSL_get_npn_negotiated_protocol(long sslNativePointer);
1131
1132    /**
1133     * Currently only intended for forcing renegotiation for testing.
1134     * Not used within OpenSSLSocketImpl.
1135     */
1136    public static native void SSL_renegotiate(long sslNativePointer) throws SSLException;
1137
1138    /**
1139     * Returns the local X509 certificate references. Must X509_free when done.
1140     */
1141    public static native long[] SSL_get_certificate(long sslNativePointer);
1142
1143    /**
1144     * Returns the peer X509 certificate references. Must X509_free when done.
1145     */
1146    public static native long[] SSL_get_peer_cert_chain(long sslNativePointer);
1147
1148    /**
1149     * Reads with the native SSL_read function from the encrypted data stream
1150     * @return -1 if error or the end of the stream is reached.
1151     */
1152    public static native int SSL_read(long sslNativePointer,
1153                                      FileDescriptor fd,
1154                                      SSLHandshakeCallbacks shc,
1155                                      byte[] b, int off, int len, int readTimeoutMillis)
1156        throws IOException;
1157
1158    public static native int SSL_read_BIO(long sslNativePointer,
1159                                          byte[] dest,
1160                                          int destOffset,
1161                                          int destLength,
1162                                          long sourceBioRef,
1163                                          long sinkBioRef,
1164                                          SSLHandshakeCallbacks shc)
1165        throws IOException;
1166
1167    /**
1168     * Writes with the native SSL_write function to the encrypted data stream.
1169     */
1170    public static native void SSL_write(long sslNativePointer,
1171                                        FileDescriptor fd,
1172                                        SSLHandshakeCallbacks shc,
1173                                        byte[] b, int off, int len, int writeTimeoutMillis)
1174        throws IOException;
1175
1176    public static native int SSL_write_BIO(long sslNativePointer,
1177                                           byte[] source,
1178                                           int length,
1179                                           long sinkBioRef,
1180                                           SSLHandshakeCallbacks shc)
1181        throws IOException;
1182
1183    public static native void SSL_interrupt(long sslNativePointer);
1184    public static native void SSL_shutdown(long sslNativePointer,
1185                                           FileDescriptor fd,
1186                                           SSLHandshakeCallbacks shc) throws IOException;
1187
1188    public static native void SSL_shutdown_BIO(long sslNativePointer,
1189                                               long sourceBioRef, long sinkBioRef,
1190                                               SSLHandshakeCallbacks shc) throws IOException;
1191
1192    public static native int SSL_get_shutdown(long sslNativePointer);
1193
1194    public static native void SSL_free(long sslNativePointer);
1195
1196    public static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
1197
1198    public static native long SSL_SESSION_get_time(long sslSessionNativePointer);
1199
1200    public static native String SSL_SESSION_get_version(long sslSessionNativePointer);
1201
1202    public static native String SSL_SESSION_cipher(long sslSessionNativePointer);
1203
1204    public static native String get_SSL_SESSION_tlsext_hostname(long sslSessionNativePointer);
1205
1206    public static native void SSL_SESSION_free(long sslSessionNativePointer);
1207
1208    public static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
1209
1210    public static native long d2i_SSL_SESSION(byte[] data) throws IOException;
1211
1212    /**
1213     * A collection of callbacks from the native OpenSSL code that are
1214     * related to the SSL handshake initiated by SSL_do_handshake.
1215     */
1216    public interface SSLHandshakeCallbacks {
1217        /**
1218         * Verify that we trust the certificate chain is trusted.
1219         *
1220         * @param sslSessionNativePtr pointer to a reference of the SSL_SESSION
1221         * @param certificateChainRefs chain of X.509 certificate references
1222         * @param authMethod auth algorithm name
1223         *
1224         * @throws CertificateException if the certificate is untrusted
1225         */
1226        public void verifyCertificateChain(long sslSessionNativePtr, long[] certificateChainRefs,
1227                String authMethod) throws CertificateException;
1228
1229        /**
1230         * Called on an SSL client when the server requests (or
1231         * requires a certificate). The client can respond by using
1232         * SSL_use_certificate and SSL_use_PrivateKey to set a
1233         * certificate if has an appropriate one available, similar to
1234         * how the server provides its certificate.
1235         *
1236         * @param keyTypes key types supported by the server,
1237         * convertible to strings with #keyType
1238         * @param asn1DerEncodedX500Principals CAs known to the server
1239         */
1240        public void clientCertificateRequested(byte[] keyTypes,
1241                                               byte[][] asn1DerEncodedX500Principals)
1242            throws CertificateEncodingException, SSLException;
1243
1244        /**
1245         * Gets the key to be used in client mode for this connection in Pre-Shared Key (PSK) key
1246         * exchange.
1247         *
1248         * @param identityHint PSK identity hint provided by the server or {@code null} if no hint
1249         *        provided.
1250         * @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)
1251         *        by this method. This identity will be provided to the server.
1252         * @param key buffer to be populated with key material by this method.
1253         *
1254         * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
1255         *         error occurred in which case the handshake will be aborted.
1256         */
1257        public int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);
1258
1259        /**
1260         * Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key
1261         * exchange.
1262         *
1263         * @param identityHint PSK identity hint provided by this server to the client or
1264         *        {@code null} if no hint was provided.
1265         * @param identity PSK identity provided by the client.
1266         * @param key buffer to be populated with key material by this method.
1267         *
1268         * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
1269         *         error occurred in which case the handshake will be aborted.
1270         */
1271        public int serverPSKKeyRequested(String identityHint, String identity, byte[] key);
1272
1273        /**
1274         * Called when SSL state changes. This could be handshake completion.
1275         */
1276        public void onSSLStateChange(long sslSessionNativePtr, int type, int val);
1277    }
1278
1279    public static native long ERR_peek_last_error();
1280
1281    public static native String SSL_CIPHER_get_kx_name(long cipherAddress);
1282
1283    public static native String[] get_cipher_names(String selection);
1284
1285    public static native byte[] get_ocsp_single_extension(byte[] ocspResponse, String oid,
1286                                                          long x509Ref, long issuerX509Ref);
1287
1288    /**
1289     * Returns the starting address of the memory region referenced by the provided direct
1290     * {@link Buffer} or {@code 0} if the provided buffer is not direct or if such access to direct
1291     * buffers is not supported by the platform.
1292     *
1293     * <p>NOTE: This method ignores the buffer's current {@code position}.
1294     */
1295    public static native long getDirectBufferAddress(Buffer buf);
1296}
1297