Home | History | Annotate | Download | only in conscrypt
      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 
     17 package org.conscrypt;
     18 
     19 import java.io.FileDescriptor;
     20 import java.io.IOException;
     21 import java.io.OutputStream;
     22 import java.net.SocketTimeoutException;
     23 import java.nio.Buffer;
     24 import java.security.InvalidAlgorithmParameterException;
     25 import java.security.InvalidKeyException;
     26 import java.security.MessageDigest;
     27 import java.security.NoSuchAlgorithmException;
     28 import java.security.PrivateKey;
     29 import java.security.SignatureException;
     30 import java.security.cert.CertificateEncodingException;
     31 import java.security.cert.CertificateException;
     32 import java.security.cert.CertificateParsingException;
     33 import java.util.ArrayList;
     34 import java.util.Calendar;
     35 import java.util.HashSet;
     36 import java.util.List;
     37 import java.util.Set;
     38 import javax.crypto.BadPaddingException;
     39 import javax.crypto.IllegalBlockSizeException;
     40 import javax.net.ssl.SSLException;
     41 import javax.security.auth.x500.X500Principal;
     42 import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException;
     43 
     44 /**
     45  * Provides the Java side of our JNI glue for OpenSSL.
     46  * <p>
     47  * Note: Many methods in this class take a reference to a Java object that holds a
     48  * native pointer in the form of a long in addition to the long itself and don't use
     49  * the Java object in the native implementation.  This is to prevent the Java object
     50  * from becoming eligible for GC while the native method is executing.  See
     51  * <a href="https://github.com/google/error-prone/blob/master/docs/bugpattern/UnsafeFinalization.md">this</a>
     52  * for more details.
     53  *
     54  * @hide
     55  */
     56 @Internal
     57 public final class NativeCrypto {
     58     // --- OpenSSL library initialization --------------------------------------
     59     private static final UnsatisfiedLinkError loadError;
     60     static {
     61         UnsatisfiedLinkError error = null;
     62         try {
     63             NativeCryptoJni.init();
     64             clinit();
     65         } catch (UnsatisfiedLinkError t) {
     66             // Don't rethrow the error, so that we can later on interrogate the
     67             // value of loadError.
     68             error = t;
     69         }
     70         loadError = error;
     71     }
     72 
     73     private native static void clinit();
     74 
     75     /**
     76      * Checks to see whether or not the native library was successfully loaded. If not, throws
     77      * the {@link UnsatisfiedLinkError} that was encountered while attempting to load the library.
     78      */
     79     static void checkAvailability() {
     80         if (loadError != null) {
     81             throw loadError;
     82         }
     83     }
     84 
     85     // --- DSA/RSA public/private key handling functions -----------------------
     86 
     87     static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
     88             byte[] dmp1, byte[] dmq1, byte[] iqmp);
     89 
     90     static native int EVP_PKEY_type(NativeRef.EVP_PKEY pkey);
     91 
     92     static native String EVP_PKEY_print_public(NativeRef.EVP_PKEY pkeyRef);
     93 
     94     static native String EVP_PKEY_print_params(NativeRef.EVP_PKEY pkeyRef);
     95 
     96     static native void EVP_PKEY_free(long pkey);
     97 
     98     static native int EVP_PKEY_cmp(NativeRef.EVP_PKEY pkey1, NativeRef.EVP_PKEY pkey2);
     99 
    100     static native byte[] EVP_marshal_private_key(NativeRef.EVP_PKEY pkey);
    101 
    102     static native long EVP_parse_private_key(byte[] data) throws ParsingException;
    103 
    104     static native byte[] EVP_marshal_public_key(NativeRef.EVP_PKEY pkey);
    105 
    106     static native long EVP_parse_public_key(byte[] data) throws ParsingException;
    107 
    108     static native long PEM_read_bio_PUBKEY(long bioCtx);
    109 
    110     static native long PEM_read_bio_PrivateKey(long bioCtx);
    111 
    112     static native long getRSAPrivateKeyWrapper(PrivateKey key, byte[] modulus);
    113 
    114     static native long getECPrivateKeyWrapper(PrivateKey key, NativeRef.EC_GROUP ecGroupRef);
    115 
    116     static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
    117 
    118     static native int RSA_size(NativeRef.EVP_PKEY pkey);
    119 
    120     static native int RSA_private_encrypt(
    121             int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, int padding);
    122 
    123     static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
    124             int padding) throws BadPaddingException, SignatureException;
    125 
    126     static native int RSA_public_encrypt(
    127             int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, int padding);
    128 
    129     static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
    130             int padding) throws BadPaddingException, SignatureException;
    131 
    132     /**
    133      * @return array of {n, e}
    134      */
    135     static native byte[][] get_RSA_public_params(NativeRef.EVP_PKEY rsa);
    136 
    137     /**
    138      * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
    139      */
    140     static native byte[][] get_RSA_private_params(NativeRef.EVP_PKEY rsa);
    141 
    142     // --- ChaCha20 -----------------------
    143 
    144     /**
    145      * Returns the encrypted or decrypted version of the data.
    146      */
    147     static native void chacha20_encrypt_decrypt(byte[] in, int inOffset, byte[] out, int outOffset,
    148             int length, byte[] key, byte[] nonce, int blockCounter);
    149 
    150     // --- EC functions --------------------------
    151 
    152     static native long EVP_PKEY_new_EC_KEY(
    153             NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pubkeyRef, byte[] privkey);
    154 
    155     static native long EC_GROUP_new_by_curve_name(String curveName);
    156 
    157     static native long EC_GROUP_new_arbitrary(
    158             byte[] p, byte[] a, byte[] b, byte[] x, byte[] y, byte[] order, int cofactor);
    159 
    160     static native String EC_GROUP_get_curve_name(NativeRef.EC_GROUP groupRef);
    161 
    162     static native byte[][] EC_GROUP_get_curve(NativeRef.EC_GROUP groupRef);
    163 
    164     static native void EC_GROUP_clear_free(long groupRef);
    165 
    166     static native long EC_GROUP_get_generator(NativeRef.EC_GROUP groupRef);
    167 
    168     static native byte[] EC_GROUP_get_order(NativeRef.EC_GROUP groupRef);
    169 
    170     static native int EC_GROUP_get_degree(NativeRef.EC_GROUP groupRef);
    171 
    172     static native byte[] EC_GROUP_get_cofactor(NativeRef.EC_GROUP groupRef);
    173 
    174     static native long EC_POINT_new(NativeRef.EC_GROUP groupRef);
    175 
    176     static native void EC_POINT_clear_free(long pointRef);
    177 
    178     static native byte[][] EC_POINT_get_affine_coordinates(
    179             NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pointRef);
    180 
    181     static native void EC_POINT_set_affine_coordinates(
    182             NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pointRef, byte[] x, byte[] y);
    183 
    184     static native long EC_KEY_generate_key(NativeRef.EC_GROUP groupRef);
    185 
    186     static native long EC_KEY_get1_group(NativeRef.EVP_PKEY pkeyRef);
    187 
    188     static native byte[] EC_KEY_get_private_key(NativeRef.EVP_PKEY keyRef);
    189 
    190     static native long EC_KEY_get_public_key(NativeRef.EVP_PKEY keyRef);
    191 
    192     static native byte[] EC_KEY_marshal_curve_name(NativeRef.EC_GROUP groupRef) throws IOException;
    193 
    194     static native long EC_KEY_parse_curve_name(byte[] encoded) throws IOException;
    195 
    196     static native int ECDH_compute_key(byte[] out, int outOffset, NativeRef.EVP_PKEY publicKeyRef,
    197             NativeRef.EVP_PKEY privateKeyRef) throws InvalidKeyException, IndexOutOfBoundsException;
    198 
    199     static native int ECDSA_size(NativeRef.EVP_PKEY pkey);
    200 
    201     static native int ECDSA_sign(byte[] data, byte[] sig, NativeRef.EVP_PKEY pkey);
    202 
    203     static native int ECDSA_verify(byte[] data, byte[] sig, NativeRef.EVP_PKEY pkey);
    204 
    205     // --- Message digest functions --------------
    206 
    207     // These return const references
    208     static native long EVP_get_digestbyname(String name);
    209 
    210     static native int EVP_MD_size(long evp_md_const);
    211 
    212     // --- Message digest context functions --------------
    213 
    214     static native long EVP_MD_CTX_create();
    215 
    216     static native void EVP_MD_CTX_cleanup(NativeRef.EVP_MD_CTX ctx);
    217 
    218     static native void EVP_MD_CTX_destroy(long ctx);
    219 
    220     static native int EVP_MD_CTX_copy_ex(
    221             NativeRef.EVP_MD_CTX dst_ctx, NativeRef.EVP_MD_CTX src_ctx);
    222 
    223     // --- Digest handling functions -------------------------------------------
    224 
    225     static native int EVP_DigestInit_ex(NativeRef.EVP_MD_CTX ctx, long evp_md);
    226 
    227     static native void EVP_DigestUpdate(
    228             NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
    229 
    230     static native void EVP_DigestUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
    231 
    232     static native int EVP_DigestFinal_ex(NativeRef.EVP_MD_CTX ctx, byte[] hash, int offset);
    233 
    234     // --- Signature handling functions ----------------------------------------
    235 
    236     static native long EVP_DigestSignInit(
    237             NativeRef.EVP_MD_CTX ctx, long evpMdRef, NativeRef.EVP_PKEY key);
    238 
    239     static native long EVP_DigestVerifyInit(
    240             NativeRef.EVP_MD_CTX ctx, long evpMdRef, NativeRef.EVP_PKEY key);
    241 
    242     static native void EVP_DigestSignUpdate(
    243             NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
    244 
    245     static native void EVP_DigestSignUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
    246 
    247     static native void EVP_DigestVerifyUpdate(
    248             NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
    249 
    250     static native void EVP_DigestVerifyUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
    251 
    252     static native byte[] EVP_DigestSignFinal(NativeRef.EVP_MD_CTX ctx);
    253 
    254     static native boolean EVP_DigestVerifyFinal(NativeRef.EVP_MD_CTX ctx, byte[] signature,
    255             int offset, int length) throws IndexOutOfBoundsException;
    256 
    257     static native long EVP_PKEY_encrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException;
    258 
    259     static native int EVP_PKEY_encrypt(NativeRef.EVP_PKEY_CTX ctx, byte[] out, int outOffset,
    260             byte[] input, int inOffset, int inLength)
    261             throws IndexOutOfBoundsException, BadPaddingException;
    262 
    263     static native long EVP_PKEY_decrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException;
    264 
    265     static native int EVP_PKEY_decrypt(NativeRef.EVP_PKEY_CTX ctx, byte[] out, int outOffset,
    266             byte[] input, int inOffset, int inLength)
    267             throws IndexOutOfBoundsException, BadPaddingException;
    268 
    269     static native void EVP_PKEY_CTX_free(long pkeyCtx);
    270 
    271     static native void EVP_PKEY_CTX_set_rsa_padding(long ctx, int pad)
    272             throws InvalidAlgorithmParameterException;
    273 
    274     static native void EVP_PKEY_CTX_set_rsa_pss_saltlen(long ctx, int len)
    275             throws InvalidAlgorithmParameterException;
    276 
    277     static native void EVP_PKEY_CTX_set_rsa_mgf1_md(long ctx, long evpMdRef)
    278             throws InvalidAlgorithmParameterException;
    279 
    280     static native void EVP_PKEY_CTX_set_rsa_oaep_md(long ctx, long evpMdRef)
    281             throws InvalidAlgorithmParameterException;
    282 
    283     static native void EVP_PKEY_CTX_set_rsa_oaep_label(long ctx, byte[] label)
    284             throws InvalidAlgorithmParameterException;
    285 
    286     // --- Block ciphers -------------------------------------------------------
    287 
    288     // These return const references
    289     static native long EVP_get_cipherbyname(String string);
    290 
    291     static native void EVP_CipherInit_ex(NativeRef.EVP_CIPHER_CTX ctx, long evpCipher, byte[] key,
    292             byte[] iv, boolean encrypting);
    293 
    294     static native int EVP_CipherUpdate(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, int outOffset,
    295             byte[] in, int inOffset, int inLength) throws IndexOutOfBoundsException;
    296 
    297     static native int EVP_CipherFinal_ex(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, int outOffset)
    298             throws BadPaddingException, IllegalBlockSizeException;
    299 
    300     static native int EVP_CIPHER_iv_length(long evpCipher);
    301 
    302     static native long EVP_CIPHER_CTX_new();
    303 
    304     static native int EVP_CIPHER_CTX_block_size(NativeRef.EVP_CIPHER_CTX ctx);
    305 
    306     static native int get_EVP_CIPHER_CTX_buf_len(NativeRef.EVP_CIPHER_CTX ctx);
    307 
    308     static native boolean get_EVP_CIPHER_CTX_final_used(NativeRef.EVP_CIPHER_CTX ctx);
    309 
    310     static native void EVP_CIPHER_CTX_set_padding(
    311             NativeRef.EVP_CIPHER_CTX ctx, boolean enablePadding);
    312 
    313     static native void EVP_CIPHER_CTX_set_key_length(NativeRef.EVP_CIPHER_CTX ctx, int keyBitSize);
    314 
    315     static native void EVP_CIPHER_CTX_free(long ctx);
    316 
    317     // --- AEAD ----------------------------------------------------------------
    318     static native long EVP_aead_aes_128_gcm();
    319 
    320     static native long EVP_aead_aes_256_gcm();
    321 
    322     static native long EVP_aead_chacha20_poly1305();
    323 
    324     static native int EVP_AEAD_max_overhead(long evpAead);
    325 
    326     static native int EVP_AEAD_nonce_length(long evpAead);
    327 
    328     static native int EVP_AEAD_CTX_seal(long evpAead, byte[] key, int tagLengthInBytes, byte[] out,
    329             int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
    330             throws BadPaddingException, IndexOutOfBoundsException;
    331 
    332     static native int EVP_AEAD_CTX_open(long evpAead, byte[] key, int tagLengthInBytes, byte[] out,
    333             int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
    334             throws BadPaddingException, IndexOutOfBoundsException;
    335 
    336     // --- HMAC functions ------------------------------------------------------
    337 
    338     static native long HMAC_CTX_new();
    339 
    340     static native void HMAC_CTX_free(long ctx);
    341 
    342     static native void HMAC_Init_ex(NativeRef.HMAC_CTX ctx, byte[] key, long evp_md);
    343 
    344     static native void HMAC_Update(NativeRef.HMAC_CTX ctx, byte[] in, int inOffset, int inLength);
    345 
    346     static native void HMAC_UpdateDirect(NativeRef.HMAC_CTX ctx, long inPtr, int inLength);
    347 
    348     static native byte[] HMAC_Final(NativeRef.HMAC_CTX ctx);
    349 
    350     // --- RAND ----------------------------------------------------------------
    351 
    352     static native void RAND_bytes(byte[] output);
    353 
    354     // --- X509_NAME -----------------------------------------------------------
    355 
    356     static int X509_NAME_hash(X500Principal principal) {
    357         return X509_NAME_hash(principal, "SHA1");
    358     }
    359 
    360     public static int X509_NAME_hash_old(X500Principal principal) {
    361         return X509_NAME_hash(principal, "MD5");
    362     }
    363     private static int X509_NAME_hash(X500Principal principal, String algorithm) {
    364         try {
    365             byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
    366             int offset = 0;
    367             return (((digest[offset++] & 0xff) << 0) | ((digest[offset++] & 0xff) << 8)
    368                     | ((digest[offset++] & 0xff) << 16) | ((digest[offset] & 0xff) << 24));
    369         } catch (NoSuchAlgorithmException e) {
    370             throw new AssertionError(e);
    371         }
    372     }
    373 
    374     // --- X509 ----------------------------------------------------------------
    375 
    376     /** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
    377     static final int GN_STACK_SUBJECT_ALT_NAME = 1;
    378 
    379     /**
    380      * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
    381      * extension.
    382      */
    383     static final int GN_STACK_ISSUER_ALT_NAME = 2;
    384 
    385     /**
    386      * Used to request only non-critical types in get_X509*_ext_oids.
    387      */
    388     static final int EXTENSION_TYPE_NON_CRITICAL = 0;
    389 
    390     /**
    391      * Used to request only critical types in get_X509*_ext_oids.
    392      */
    393     static final int EXTENSION_TYPE_CRITICAL = 1;
    394 
    395     static native long d2i_X509_bio(long bioCtx);
    396 
    397     static native long d2i_X509(byte[] encoded) throws ParsingException;
    398 
    399     static native long PEM_read_bio_X509(long bioCtx);
    400 
    401     static native byte[] i2d_X509(long x509ctx, OpenSSLX509Certificate holder);
    402 
    403     /** Takes an X509 context not an X509_PUBKEY context. */
    404     static native byte[] i2d_X509_PUBKEY(long x509ctx, OpenSSLX509Certificate holder);
    405 
    406     static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
    407 
    408     static native long[] ASN1_seq_unpack_X509_bio(long bioRef) throws ParsingException;
    409 
    410     static native void X509_free(long x509ctx, OpenSSLX509Certificate holder);
    411 
    412     static native long X509_dup(long x509ctx, OpenSSLX509Certificate holder);
    413 
    414     static native int X509_cmp(long x509ctx1, OpenSSLX509Certificate holder, long x509ctx2, OpenSSLX509Certificate holder2);
    415 
    416     static native void X509_print_ex(long bioCtx, long x509ctx, OpenSSLX509Certificate holder, long nmflag, long certflag);
    417 
    418     static native byte[] X509_get_issuer_name(long x509ctx, OpenSSLX509Certificate holder);
    419 
    420     static native byte[] X509_get_subject_name(long x509ctx, OpenSSLX509Certificate holder);
    421 
    422     static native String get_X509_sig_alg_oid(long x509ctx, OpenSSLX509Certificate holder);
    423 
    424     static native byte[] get_X509_sig_alg_parameter(long x509ctx, OpenSSLX509Certificate holder);
    425 
    426     static native boolean[] get_X509_issuerUID(long x509ctx, OpenSSLX509Certificate holder);
    427 
    428     static native boolean[] get_X509_subjectUID(long x509ctx, OpenSSLX509Certificate holder);
    429 
    430     static native long X509_get_pubkey(long x509ctx, OpenSSLX509Certificate holder)
    431             throws NoSuchAlgorithmException, InvalidKeyException;
    432 
    433     static native String get_X509_pubkey_oid(long x509ctx, OpenSSLX509Certificate holder);
    434 
    435     static native byte[] X509_get_ext_oid(long x509ctx, OpenSSLX509Certificate holder, String oid);
    436 
    437     static native String[] get_X509_ext_oids(long x509ctx, OpenSSLX509Certificate holder, int critical);
    438 
    439     static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, OpenSSLX509Certificate holder, int type)
    440             throws CertificateParsingException;
    441 
    442     static native boolean[] get_X509_ex_kusage(long x509ctx, OpenSSLX509Certificate holder);
    443 
    444     static native String[] get_X509_ex_xkusage(long x509ctx, OpenSSLX509Certificate holder);
    445 
    446     static native int get_X509_ex_pathlen(long x509ctx, OpenSSLX509Certificate holder);
    447 
    448     static native long X509_get_notBefore(long x509ctx, OpenSSLX509Certificate holder);
    449 
    450     static native long X509_get_notAfter(long x509ctx, OpenSSLX509Certificate holder);
    451 
    452     static native long X509_get_version(long x509ctx, OpenSSLX509Certificate holder);
    453 
    454     static native byte[] X509_get_serialNumber(long x509ctx, OpenSSLX509Certificate holder);
    455 
    456     static native void X509_verify(long x509ctx, OpenSSLX509Certificate holder, NativeRef.EVP_PKEY pkeyCtx)
    457             throws BadPaddingException;
    458 
    459     static native byte[] get_X509_cert_info_enc(long x509ctx, OpenSSLX509Certificate holder);
    460 
    461     static native byte[] get_X509_signature(long x509ctx, OpenSSLX509Certificate holder);
    462 
    463     static native int get_X509_ex_flags(long x509ctx, OpenSSLX509Certificate holder);
    464 
    465     // Used by Android platform TrustedCertificateStore.
    466     @SuppressWarnings("unused")
    467     static native int X509_check_issued(long ctx, OpenSSLX509Certificate holder, long ctx2, OpenSSLX509Certificate holder2);
    468 
    469     // --- PKCS7 ---------------------------------------------------------------
    470 
    471     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    472     static final int PKCS7_CERTS = 1;
    473 
    474     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    475     static final int PKCS7_CRLS = 2;
    476 
    477     /** Returns an array of X509 or X509_CRL pointers. */
    478     static native long[] d2i_PKCS7_bio(long bioCtx, int which) throws ParsingException;
    479 
    480     /** Returns an array of X509 or X509_CRL pointers. */
    481     static native byte[] i2d_PKCS7(long[] certs);
    482 
    483     /** Returns an array of X509 or X509_CRL pointers. */
    484     static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
    485 
    486     // --- X509_CRL ------------------------------------------------------------
    487 
    488     static native long d2i_X509_CRL_bio(long bioCtx);
    489 
    490     static native long PEM_read_bio_X509_CRL(long bioCtx);
    491 
    492     static native byte[] i2d_X509_CRL(long x509CrlCtx, OpenSSLX509CRL holder);
    493 
    494     static native void X509_CRL_free(long x509CrlCtx, OpenSSLX509CRL holder);
    495 
    496     static native void X509_CRL_print(long bioCtx, long x509CrlCtx, OpenSSLX509CRL holder);
    497 
    498     static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx, OpenSSLX509CRL holder);
    499 
    500     static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx, OpenSSLX509CRL holder);
    501 
    502     static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx, OpenSSLX509CRL holder);
    503 
    504     /** Returns X509_REVOKED reference that is not duplicated! */
    505     static native long X509_CRL_get0_by_cert(long x509CrlCtx, OpenSSLX509CRL holder, long x509Ctx, OpenSSLX509Certificate holder2);
    506 
    507     /** Returns X509_REVOKED reference that is not duplicated! */
    508     static native long X509_CRL_get0_by_serial(long x509CrlCtx, OpenSSLX509CRL holder, byte[] serial);
    509 
    510     /** Returns an array of X509_REVOKED that are owned by the caller. */
    511     static native long[] X509_CRL_get_REVOKED(long x509CrlCtx, OpenSSLX509CRL holder);
    512 
    513     static native String[] get_X509_CRL_ext_oids(long x509Crlctx, OpenSSLX509CRL holder, int critical);
    514 
    515     static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, OpenSSLX509CRL holder, String oid);
    516 
    517     static native void X509_delete_ext(long x509, OpenSSLX509Certificate holder, String oid);
    518 
    519     static native long X509_CRL_get_version(long x509CrlCtx, OpenSSLX509CRL holder);
    520 
    521     static native long X509_CRL_get_ext(long x509CrlCtx, OpenSSLX509CRL holder, String oid);
    522 
    523     static native byte[] get_X509_CRL_signature(long x509ctx, OpenSSLX509CRL holder);
    524 
    525     static native void X509_CRL_verify(long x509CrlCtx, OpenSSLX509CRL holder, NativeRef.EVP_PKEY pkeyCtx);
    526 
    527     static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx, OpenSSLX509CRL holder);
    528 
    529     static native long X509_CRL_get_lastUpdate(long x509CrlCtx, OpenSSLX509CRL holder);
    530 
    531     static native long X509_CRL_get_nextUpdate(long x509CrlCtx, OpenSSLX509CRL holder);
    532 
    533     // --- X509_REVOKED --------------------------------------------------------
    534 
    535     static native long X509_REVOKED_dup(long x509RevokedCtx);
    536 
    537     static native byte[] i2d_X509_REVOKED(long x509RevokedCtx);
    538 
    539     static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical);
    540 
    541     static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid);
    542 
    543     static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx);
    544 
    545     static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid);
    546 
    547     /** Returns ASN1_TIME reference. */
    548     static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx);
    549 
    550     static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx);
    551 
    552     // --- X509_EXTENSION ------------------------------------------------------
    553 
    554     static native int X509_supported_extension(long x509ExtensionRef);
    555 
    556     // --- ASN1_TIME -----------------------------------------------------------
    557 
    558     static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal) throws ParsingException;
    559 
    560     // --- ASN1 Encoding -------------------------------------------------------
    561 
    562     /**
    563      * Allocates and returns an opaque reference to an object that can be used with other
    564      * asn1_read_* functions to read the ASN.1-encoded data in val.  The returned object must
    565      * be freed after use by calling asn1_read_free.
    566      */
    567     static native long asn1_read_init(byte[] val) throws IOException;
    568 
    569     /**
    570      * Allocates and returns an opaque reference to an object that can be used with other
    571      * asn1_read_* functions to read the ASN.1 sequence pointed to by cbsRef.  The returned
    572      * object must be freed after use by calling asn1_read_free.
    573      */
    574     static native long asn1_read_sequence(long cbsRef) throws IOException;
    575 
    576     /**
    577      * Returns whether the next object in the given reference is explicitly tagged with the
    578      * given tag number.
    579      */
    580     static native boolean asn1_read_next_tag_is(long cbsRef, int tag) throws IOException;
    581 
    582     /**
    583      * Allocates and returns an opaque reference to an object that can be used with
    584      * other asn1_read_* functions to read the ASN.1 data pointed to by cbsRef.  The returned
    585      * object must be freed after use by calling asn1_read_free.
    586      */
    587     static native long asn1_read_tagged(long cbsRef) throws IOException;
    588 
    589     /**
    590      * Returns the contents of an ASN.1 octet string from the given reference.
    591      */
    592     static native byte[] asn1_read_octetstring(long cbsRef) throws IOException;
    593 
    594     /**
    595      * Returns an ASN.1 integer from the given reference.  If the integer doesn't fit
    596      * in a uint64, this method will throw an IOException.
    597      */
    598     static native long asn1_read_uint64(long cbsRef) throws IOException;
    599 
    600     /**
    601      * Consumes an ASN.1 NULL from the given reference.
    602      */
    603     static native void asn1_read_null(long cbsRef) throws IOException;
    604 
    605     /**
    606      * Returns an ASN.1 OID in dotted-decimal notation (eg, "1.3.14.3.2.26" for SHA-1) from the
    607      * given reference.
    608      */
    609     static native String asn1_read_oid(long cbsRef) throws IOException;
    610 
    611     /**
    612      * Returns whether or not the given reference has been read completely.
    613      */
    614     static native boolean asn1_read_is_empty(long cbsRef);
    615 
    616     /**
    617      * Frees any resources associated with the given reference.  After calling, the reference
    618      * must not be used again.  This may be called with a zero reference, in which case nothing
    619      * will be done.
    620      */
    621     static native void asn1_read_free(long cbsRef);
    622 
    623     /**
    624      * Allocates and returns an opaque reference to an object that can be used with other
    625      * asn1_write_* functions to write ASN.1-encoded data.  The returned object must be finalized
    626      * after use by calling either asn1_write_finish or asn1_write_cleanup, and its resources
    627      * must be freed by calling asn1_write_free.
    628      */
    629     static native long asn1_write_init() throws IOException;
    630 
    631     /**
    632      * Allocates and returns an opaque reference to an object that can be used with other
    633      * asn1_write_* functions to write an ASN.1 sequence into the given reference.  The returned
    634      * reference may only be used until the next call on the parent reference.  The returned
    635      * object must be freed after use by calling asn1_write_free.
    636      */
    637     static native long asn1_write_sequence(long cbbRef) throws IOException;
    638 
    639     /**
    640      * Allocates and returns an opaque reference to an object that can be used with other
    641      * asn1_write_* functions to write a explicitly-tagged ASN.1 object with the given tag
    642      * into the given reference. The returned reference may only be used until the next
    643      * call on the parent reference.  The returned object must be freed after use by
    644      * calling asn1_write_free.
    645      */
    646     static native long asn1_write_tag(long cbbRef, int tag) throws IOException;
    647 
    648     /**
    649      * Writes the given data into the given reference as an ASN.1-encoded octet string.
    650      */
    651     static native void asn1_write_octetstring(long cbbRef, byte[] data) throws IOException;
    652 
    653     /**
    654      * Writes the given value into the given reference as an ASN.1-encoded integer.
    655      */
    656     static native void asn1_write_uint64(long cbbRef, long value) throws IOException;
    657 
    658     /**
    659      * Writes a NULL value into the given reference.
    660      */
    661     static native void asn1_write_null(long cbbRef) throws IOException;
    662 
    663     /**
    664      * Writes the given OID (which must be in dotted-decimal notation) into the given reference.
    665      */
    666     static native void asn1_write_oid(long cbbRef, String oid) throws IOException;
    667 
    668     /**
    669      * Flushes the given reference, invalidating any child references and completing their
    670      * operations.  This must be called if the child references are to be freed before
    671      * asn1_write_finish is called on the ultimate parent.  The child references must still
    672      * be freed.
    673      */
    674     static native void asn1_write_flush(long cbbRef) throws IOException;
    675 
    676     /**
    677      * Completes any in-progress operations and returns the ASN.1-encoded data.  Either this
    678      * or asn1_write_cleanup must be called on any reference returned from asn1_write_init
    679      * before it is freed.
    680      */
    681     static native byte[] asn1_write_finish(long cbbRef) throws IOException;
    682 
    683     /**
    684      * Cleans up intermediate state in the given reference.  Either this or asn1_write_finish
    685      * must be called on any reference returned from asn1_write_init before it is freed.
    686      */
    687     static native void asn1_write_cleanup(long cbbRef);
    688 
    689     /**
    690      * Frees resources associated with the given reference.  After calling, the reference
    691      * must not be used again.  This may be called with a zero reference, in which case nothing
    692      * will be done.
    693      */
    694     static native void asn1_write_free(long cbbRef);
    695 
    696     // --- BIO stream creation -------------------------------------------------
    697 
    698     static native long create_BIO_InputStream(OpenSSLBIOInputStream is, boolean isFinite);
    699 
    700     static native long create_BIO_OutputStream(OutputStream os);
    701 
    702     static native void BIO_free_all(long bioRef);
    703 
    704     // --- SSL handling --------------------------------------------------------
    705 
    706     static final String OBSOLETE_PROTOCOL_SSLV3 = "SSLv3";
    707     private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
    708     private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
    709     private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
    710 
    711     // SUPPORTED_CIPHER_SUITES_SET contains all the supported cipher suites, using their Java names.
    712     static final Set<String> SUPPORTED_CIPHER_SUITES_SET = new HashSet<String>();
    713 
    714     // SUPPORTED_LEGACY_CIPHER_SUITES_SET contains all the supported cipher suites using the legacy
    715     // OpenSSL-style names.
    716     private static final Set<String> SUPPORTED_LEGACY_CIPHER_SUITES_SET = new HashSet<String>();
    717 
    718     /**
    719      * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
    720      * indication signaling cipher suite value. It is not a real
    721      * cipher suite. It is just an indication in the default and
    722      * supported cipher suite lists indicates that the implementation
    723      * supports secure renegotiation.
    724      * <p>
    725      * In the RI, its presence means that the SCSV is sent in the
    726      * cipher suite list to indicate secure renegotiation support and
    727      * its absense means to send an empty TLS renegotiation info
    728      * extension instead.
    729      * <p>
    730      * However, OpenSSL doesn't provide an API to give this level of
    731      * control, instead always sending the SCSV and always including
    732      * the empty renegotiation info if TLS is used (as opposed to
    733      * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
    734      * be passed for compatibility as to provide the hint that we
    735      * support secure renegotiation.
    736      */
    737     static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
    738 
    739     static String cipherSuiteToJava(String cipherSuite) {
    740         // For historical reasons, Java uses a different name for TLS_RSA_WITH_3DES_EDE_CBC_SHA.
    741         if ("TLS_RSA_WITH_3DES_EDE_CBC_SHA".equals(cipherSuite)) {
    742             return "SSL_RSA_WITH_3DES_EDE_CBC_SHA";
    743         }
    744         return cipherSuite;
    745     }
    746 
    747     static String cipherSuiteFromJava(String javaCipherSuite) {
    748         if ("SSL_RSA_WITH_3DES_EDE_CBC_SHA".equals(javaCipherSuite)) {
    749             return "TLS_RSA_WITH_3DES_EDE_CBC_SHA";
    750         }
    751         return javaCipherSuite;
    752     }
    753 
    754     /**
    755      * TLS_FALLBACK_SCSV is from
    756      * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
    757      * to indicate to the server that this is a fallback protocol
    758      * request.
    759      */
    760     private static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV";
    761 
    762     private static final String[] SUPPORTED_CIPHER_SUITES;
    763     static {
    764         String[] allCipherSuites = get_cipher_names("ALL:!DHE");
    765 
    766         // get_cipher_names returns an array where even indices are the standard name and odd
    767         // indices are the OpenSSL name.
    768         int size = allCipherSuites.length;
    769         if (size % 2 != 0) {
    770             throw new IllegalArgumentException("Invalid cipher list returned by get_cipher_names");
    771         }
    772         SUPPORTED_CIPHER_SUITES = new String[size / 2 + 2];
    773         for (int i = 0; i < size; i += 2) {
    774             String cipherSuite = cipherSuiteToJava(allCipherSuites[i]);
    775             SUPPORTED_CIPHER_SUITES[i / 2] = cipherSuite;
    776             SUPPORTED_CIPHER_SUITES_SET.add(cipherSuite);
    777 
    778             SUPPORTED_LEGACY_CIPHER_SUITES_SET.add(allCipherSuites[i + 1]);
    779         }
    780         SUPPORTED_CIPHER_SUITES[size / 2] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
    781         SUPPORTED_CIPHER_SUITES[size / 2 + 1] = TLS_FALLBACK_SCSV;
    782     }
    783 
    784     /**
    785      * Returns 1 if the BoringSSL believes the CPU has AES accelerated hardware
    786      * instructions. Used to determine cipher suite ordering.
    787      */
    788     static native int EVP_has_aes_hardware();
    789 
    790     static native long SSL_CTX_new();
    791 
    792     // IMPLEMENTATION NOTE: The default list of cipher suites is a trade-off between what we'd like
    793     // to use and what servers currently support. We strive to be secure enough by default. We thus
    794     // avoid unacceptably weak suites (e.g., those with bulk cipher secret key shorter than 128
    795     // bits), while maintaining the capability to connect to the majority of servers.
    796     //
    797     // Cipher suites are listed in preference order (favorite choice first) of the client. However,
    798     // servers are not required to honor the order. The key rules governing the preference order
    799     // are:
    800     // * Prefer Forward Secrecy (i.e., cipher suites that use ECDHE and DHE for key agreement).
    801     // * Prefer ChaCha20-Poly1305 to AES-GCM unless hardware support for AES is available.
    802     // * Prefer AES-GCM to AES-CBC whose MAC-pad-then-encrypt approach leads to weaknesses (e.g.,
    803     //   Lucky 13).
    804     // * Prefer 128-bit bulk encryption to 256-bit one, because 128-bit is safe enough while
    805     //   consuming less CPU/time/energy.
    806     //
    807     // NOTE: Removing cipher suites from this list needs to be done with caution, because this may
    808     // prevent apps from connecting to servers they were previously able to connect to.
    809 
    810     /** X.509 based cipher suites enabled by default (if requested), in preference order. */
    811     private static final boolean HAS_AES_HARDWARE = EVP_has_aes_hardware() == 1;
    812     static final String[] DEFAULT_X509_CIPHER_SUITES = HAS_AES_HARDWARE ?
    813             new String[] {
    814                     "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
    815                     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
    816                     "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
    817                     "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
    818                     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
    819                     "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
    820                     "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
    821                     "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
    822                     "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
    823                     "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
    824                     "TLS_RSA_WITH_AES_128_GCM_SHA256",
    825                     "TLS_RSA_WITH_AES_256_GCM_SHA384",
    826                     "TLS_RSA_WITH_AES_128_CBC_SHA",
    827                     "TLS_RSA_WITH_AES_256_CBC_SHA",
    828             } :
    829             new String[] {
    830                     "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
    831                     "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
    832                     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
    833                     "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
    834                     "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
    835                     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
    836                     "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
    837                     "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
    838                     "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
    839                     "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
    840                     "TLS_RSA_WITH_AES_128_GCM_SHA256",
    841                     "TLS_RSA_WITH_AES_256_GCM_SHA384",
    842                     "TLS_RSA_WITH_AES_128_CBC_SHA",
    843                     "TLS_RSA_WITH_AES_256_CBC_SHA",
    844             };
    845 
    846     /** TLS-PSK cipher suites enabled by default (if requested), in preference order. */
    847     static final String[] DEFAULT_PSK_CIPHER_SUITES = new String[] {
    848             "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
    849             "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
    850             "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
    851             "TLS_PSK_WITH_AES_128_CBC_SHA",
    852             "TLS_PSK_WITH_AES_256_CBC_SHA",
    853     };
    854 
    855     static String[] getSupportedCipherSuites() {
    856         return SUPPORTED_CIPHER_SUITES.clone();
    857     }
    858 
    859     static native void SSL_CTX_free(long ssl_ctx, AbstractSessionContext holder);
    860 
    861     static native void SSL_CTX_set_session_id_context(long ssl_ctx, AbstractSessionContext holder, byte[] sid_ctx);
    862 
    863     static native long SSL_CTX_set_timeout(long ssl_ctx, AbstractSessionContext holder, long seconds);
    864 
    865     static native long SSL_new(long ssl_ctx, AbstractSessionContext holder) throws SSLException;
    866 
    867     static native void SSL_enable_tls_channel_id(long ssl, NativeSsl ssl_holder) throws SSLException;
    868 
    869     static native byte[] SSL_get_tls_channel_id(long ssl, NativeSsl ssl_holder) throws SSLException;
    870 
    871     static native void SSL_set1_tls_channel_id(long ssl, NativeSsl ssl_holder, NativeRef.EVP_PKEY pkey);
    872 
    873     /**
    874      * Sets the local certificates and private key.
    875      *
    876      * @param ssl the SSL reference.
    877      * @param encodedCertificates the encoded form of the local certificate chain.
    878      * @param pkey a reference to the private key.
    879      * @throws SSLException if a problem occurs setting the cert/key.
    880      */
    881     static native void setLocalCertsAndPrivateKey(long ssl, NativeSsl ssl_holder, byte[][] encodedCertificates,
    882         NativeRef.EVP_PKEY pkey) throws SSLException;
    883 
    884     static native void SSL_set_client_CA_list(long ssl, NativeSsl ssl_holder, byte[][] asn1DerEncodedX500Principals)
    885             throws SSLException;
    886 
    887     static native long SSL_set_mode(long ssl, NativeSsl ssl_holder, long mode);
    888 
    889     static native long SSL_set_options(long ssl, NativeSsl ssl_holder, long options);
    890 
    891     static native long SSL_clear_options(long ssl, NativeSsl ssl_holder, long options);
    892 
    893     static native void SSL_enable_signed_cert_timestamps(long ssl, NativeSsl ssl_holder);
    894 
    895     static native byte[] SSL_get_signed_cert_timestamp_list(long ssl, NativeSsl ssl_holder);
    896 
    897     static native void SSL_set_signed_cert_timestamp_list(long ssl, NativeSsl ssl_holder, byte[] list);
    898 
    899     static native void SSL_enable_ocsp_stapling(long ssl, NativeSsl ssl_holder);
    900 
    901     static native byte[] SSL_get_ocsp_response(long ssl, NativeSsl ssl_holder);
    902 
    903     static native void SSL_set_ocsp_response(long ssl, NativeSsl ssl_holder, byte[] response);
    904 
    905     static native byte[] SSL_get_tls_unique(long ssl, NativeSsl ssl_holder);
    906 
    907     static native void SSL_use_psk_identity_hint(long ssl, NativeSsl ssl_holder, String identityHint) throws SSLException;
    908 
    909     static native void set_SSL_psk_client_callback_enabled(long ssl, NativeSsl ssl_holder, boolean enabled);
    910 
    911     static native void set_SSL_psk_server_callback_enabled(long ssl, NativeSsl ssl_holder, boolean enabled);
    912 
    913     /** Protocols to enable by default when "TLSv1.2" is requested. */
    914     static final String[] TLSV12_PROTOCOLS = new String[] {
    915             SUPPORTED_PROTOCOL_TLSV1,
    916             SUPPORTED_PROTOCOL_TLSV1_1,
    917             SUPPORTED_PROTOCOL_TLSV1_2,
    918     };
    919 
    920     /** Protocols to enable by default when "TLSv1.1" is requested. */
    921     static final String[] TLSV11_PROTOCOLS = new String[] {
    922             SUPPORTED_PROTOCOL_TLSV1,
    923             SUPPORTED_PROTOCOL_TLSV1_1,
    924             SUPPORTED_PROTOCOL_TLSV1_2,
    925     };
    926 
    927     /** Protocols to enable by default when "TLSv1" is requested. */
    928     static final String[] TLSV1_PROTOCOLS = new String[] {
    929             SUPPORTED_PROTOCOL_TLSV1,
    930             SUPPORTED_PROTOCOL_TLSV1_1,
    931             SUPPORTED_PROTOCOL_TLSV1_2,
    932     };
    933 
    934     static final String[] DEFAULT_PROTOCOLS = TLSV12_PROTOCOLS;
    935 
    936     static String[] getSupportedProtocols() {
    937         return TLSV12_PROTOCOLS.clone();
    938     }
    939 
    940     static void setEnabledProtocols(long ssl, NativeSsl ssl_holder, String[] protocols) {
    941         checkEnabledProtocols(protocols);
    942         // openssl uses negative logic letting you disable protocols.
    943         // so first, assume we need to set all (disable all) and clear none (enable none).
    944         // in the loop, selectively move bits from set to clear (from disable to enable)
    945         long optionsToSet = (NativeConstants.SSL_OP_NO_SSLv3 | NativeConstants.SSL_OP_NO_TLSv1
    946                 | NativeConstants.SSL_OP_NO_TLSv1_1 | NativeConstants.SSL_OP_NO_TLSv1_2);
    947         long optionsToClear = 0;
    948         for (String protocol : protocols) {
    949             if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
    950                 optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1;
    951                 optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1;
    952             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
    953                 optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1_1;
    954                 optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1_1;
    955             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
    956                 optionsToSet &= ~NativeConstants.SSL_OP_NO_TLSv1_2;
    957                 optionsToClear |= NativeConstants.SSL_OP_NO_TLSv1_2;
    958             } else if (protocol.equals(OBSOLETE_PROTOCOL_SSLV3)) {
    959                 // Do nothing since we no longer support this protocol, but
    960                 // allow it in the list of protocols so we can give an error
    961                 // message about it if the handshake fails.
    962             } else {
    963                 // error checked by checkEnabledProtocols
    964                 throw new IllegalStateException();
    965             }
    966         }
    967 
    968         SSL_set_options(ssl, ssl_holder, optionsToSet);
    969         SSL_clear_options(ssl, ssl_holder, optionsToClear);
    970     }
    971 
    972     static String[] checkEnabledProtocols(String[] protocols) {
    973         if (protocols == null) {
    974             throw new IllegalArgumentException("protocols == null");
    975         }
    976         for (String protocol : protocols) {
    977             if (protocol == null) {
    978                 throw new IllegalArgumentException("protocols contains null");
    979             }
    980             if (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1)
    981                     && !protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)
    982                     && !protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)
    983                     && !protocol.equals(OBSOLETE_PROTOCOL_SSLV3)) {
    984                 throw new IllegalArgumentException("protocol " + protocol + " is not supported");
    985             }
    986         }
    987         return protocols;
    988     }
    989 
    990     static native void SSL_set_cipher_lists(long ssl, NativeSsl ssl_holder, String[] ciphers);
    991 
    992     /**
    993      * Gets the list of cipher suites enabled for the provided {@code SSL} instance.
    994      *
    995      * @return array of {@code SSL_CIPHER} references.
    996      */
    997     static native long[] SSL_get_ciphers(long ssl, NativeSsl ssl_holder);
    998 
    999     static void setEnabledCipherSuites(long ssl, NativeSsl ssl_holder, String[] cipherSuites) {
   1000         checkEnabledCipherSuites(cipherSuites);
   1001         List<String> opensslSuites = new ArrayList<String>();
   1002         for (int i = 0; i < cipherSuites.length; i++) {
   1003             String cipherSuite = cipherSuites[i];
   1004             if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
   1005                 continue;
   1006             }
   1007             if (cipherSuite.equals(TLS_FALLBACK_SCSV)) {
   1008                 SSL_set_mode(ssl, ssl_holder, NativeConstants.SSL_MODE_SEND_FALLBACK_SCSV);
   1009                 continue;
   1010             }
   1011             opensslSuites.add(cipherSuiteFromJava(cipherSuite));
   1012         }
   1013         SSL_set_cipher_lists(ssl, ssl_holder, opensslSuites.toArray(new String[opensslSuites.size()]));
   1014     }
   1015 
   1016     static String[] checkEnabledCipherSuites(String[] cipherSuites) {
   1017         if (cipherSuites == null) {
   1018             throw new IllegalArgumentException("cipherSuites == null");
   1019         }
   1020         // makes sure all suites are valid, throwing on error
   1021         for (int i = 0; i < cipherSuites.length; i++) {
   1022             if (cipherSuites[i] == null) {
   1023                 throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
   1024             }
   1025             if (cipherSuites[i].equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
   1026                     || cipherSuites[i].equals(TLS_FALLBACK_SCSV)) {
   1027                 continue;
   1028             }
   1029             if (SUPPORTED_CIPHER_SUITES_SET.contains(cipherSuites[i])) {
   1030                 continue;
   1031             }
   1032 
   1033             // For backwards compatibility, it's allowed for |cipherSuite| to
   1034             // be an OpenSSL-style cipher-suite name.
   1035             if (SUPPORTED_LEGACY_CIPHER_SUITES_SET.contains(cipherSuites[i])) {
   1036                 // TODO log warning about using backward compatability
   1037                 continue;
   1038             }
   1039             throw new IllegalArgumentException(
   1040                     "cipherSuite " + cipherSuites[i] + " is not supported.");
   1041         }
   1042         return cipherSuites;
   1043     }
   1044 
   1045     static native void SSL_set_accept_state(long ssl, NativeSsl ssl_holder);
   1046 
   1047     static native void SSL_set_connect_state(long ssl, NativeSsl ssl_holder);
   1048 
   1049     static native void SSL_set_verify(long ssl, NativeSsl ssl_holder, int mode);
   1050 
   1051     static native void SSL_set_session(long ssl, NativeSsl ssl_holder, long sslSessionNativePointer)
   1052             throws SSLException;
   1053 
   1054     static native void SSL_set_session_creation_enabled(
   1055             long ssl, NativeSsl ssl_holder, boolean creationEnabled) throws SSLException;
   1056 
   1057     static native boolean SSL_session_reused(long ssl, NativeSsl ssl_holder);
   1058 
   1059     static native void SSL_accept_renegotiations(long ssl, NativeSsl ssl_holder) throws SSLException;
   1060 
   1061     static native void SSL_set_tlsext_host_name(long ssl, NativeSsl ssl_holder, String hostname)
   1062             throws SSLException;
   1063     static native String SSL_get_servername(long ssl, NativeSsl ssl_holder);
   1064 
   1065     static native void SSL_do_handshake(
   1066             long ssl, NativeSsl ssl_holder, FileDescriptor fd, SSLHandshakeCallbacks shc, int timeoutMillis)
   1067             throws SSLException, SocketTimeoutException, CertificateException;
   1068 
   1069     public static native String SSL_get_current_cipher(long ssl, NativeSsl ssl_holder);
   1070 
   1071     public static native String SSL_get_version(long ssl, NativeSsl ssl_holder);
   1072 
   1073     /**
   1074      * Returns the peer certificate chain.
   1075      */
   1076     static native byte[][] SSL_get0_peer_certificates(long ssl, NativeSsl ssl_holder);
   1077 
   1078     /**
   1079      * Reads with the native SSL_read function from the encrypted data stream
   1080      * @return -1 if error or the end of the stream is reached.
   1081      */
   1082     static native int SSL_read(long ssl, NativeSsl ssl_holder, FileDescriptor fd, SSLHandshakeCallbacks shc,
   1083             byte[] b, int off, int len, int readTimeoutMillis) throws IOException;
   1084 
   1085     /**
   1086      * Writes with the native SSL_write function to the encrypted data stream.
   1087      */
   1088     static native void SSL_write(long ssl, NativeSsl ssl_holder, FileDescriptor fd,
   1089             SSLHandshakeCallbacks shc, byte[] b, int off, int len, int writeTimeoutMillis)
   1090             throws IOException;
   1091 
   1092     static native void SSL_interrupt(long ssl, NativeSsl ssl_holder);
   1093     static native void SSL_shutdown(
   1094             long ssl, NativeSsl ssl_holder, FileDescriptor fd, SSLHandshakeCallbacks shc) throws IOException;
   1095 
   1096     static native int SSL_get_shutdown(long ssl, NativeSsl ssl_holder);
   1097 
   1098     static native void SSL_free(long ssl, NativeSsl ssl_holder);
   1099 
   1100     static native long SSL_get_time(long ssl, NativeSsl ssl_holder);
   1101 
   1102     static native long SSL_set_timeout(long ssl, NativeSsl ssl_holder, long millis);
   1103 
   1104     static native long SSL_get_timeout(long ssl, NativeSsl ssl_holder);
   1105 
   1106     static native byte[] SSL_session_id(long ssl, NativeSsl ssl_holder);
   1107 
   1108     static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
   1109 
   1110     static native long SSL_SESSION_get_time(long sslSessionNativePointer);
   1111 
   1112     static native long SSL_SESSION_get_timeout(long sslSessionNativePointer);
   1113 
   1114     static native String SSL_SESSION_get_version(long sslSessionNativePointer);
   1115 
   1116     static native String SSL_SESSION_cipher(long sslSessionNativePointer);
   1117 
   1118     static native void SSL_SESSION_up_ref(long sslSessionNativePointer);
   1119 
   1120     static native void SSL_SESSION_free(long sslSessionNativePointer);
   1121 
   1122     static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
   1123 
   1124     static native long d2i_SSL_SESSION(byte[] data) throws IOException;
   1125 
   1126     /**
   1127      * A collection of callbacks from the native OpenSSL code that are
   1128      * related to the SSL handshake initiated by SSL_do_handshake.
   1129      */
   1130     interface SSLHandshakeCallbacks {
   1131         /**
   1132          * Verify that the certificate chain is trusted.
   1133          *
   1134          * @param certificateChain chain of X.509 certificates in their encoded form
   1135          * @param authMethod auth algorithm name
   1136          *
   1137          * @throws CertificateException if the certificate is untrusted
   1138          */
   1139         @SuppressWarnings("unused")
   1140         void verifyCertificateChain(byte[][] certificateChain, String authMethod)
   1141                 throws CertificateException;
   1142 
   1143         /**
   1144          * Called on an SSL client when the server requests (or
   1145          * requires a certificate). The client can respond by using
   1146          * SSL_use_certificate and SSL_use_PrivateKey to set a
   1147          * certificate if has an appropriate one available, similar to
   1148          * how the server provides its certificate.
   1149          *
   1150          * @param keyTypes key types supported by the server,
   1151          * convertible to strings with #keyType
   1152          * @param asn1DerEncodedX500Principals CAs known to the server
   1153          */
   1154         @SuppressWarnings("unused")
   1155         void clientCertificateRequested(byte[] keyTypes, byte[][] asn1DerEncodedX500Principals)
   1156                 throws CertificateEncodingException, SSLException;
   1157 
   1158         /**
   1159          * Gets the key to be used in client mode for this connection in Pre-Shared Key (PSK) key
   1160          * exchange.
   1161          *
   1162          * @param identityHint PSK identity hint provided by the server or {@code null} if no hint
   1163          *        provided.
   1164          * @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)
   1165          *        by this method. This identity will be provided to the server.
   1166          * @param key buffer to be populated with key material by this method.
   1167          *
   1168          * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
   1169          *         error occurred in which case the handshake will be aborted.
   1170          */
   1171         int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);
   1172 
   1173         /**
   1174          * Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key
   1175          * exchange.
   1176          *
   1177          * @param identityHint PSK identity hint provided by this server to the client or
   1178          *        {@code null} if no hint was provided.
   1179          * @param identity PSK identity provided by the client.
   1180          * @param key buffer to be populated with key material by this method.
   1181          *
   1182          * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
   1183          *         error occurred in which case the handshake will be aborted.
   1184          */
   1185         int serverPSKKeyRequested(String identityHint, String identity, byte[] key);
   1186 
   1187         /**
   1188          * Called when SSL state changes. This could be handshake completion.
   1189          */
   1190         @SuppressWarnings("unused")
   1191         void onSSLStateChange(int type, int val);
   1192 
   1193         /**
   1194          * Called when a new session has been established and may be added to the session cache.
   1195          * The callee is responsible for incrementing the reference count on the returned session.
   1196          */
   1197         @SuppressWarnings("unused")
   1198         void onNewSessionEstablished(long sslSessionNativePtr);
   1199 
   1200         /**
   1201          * Called for servers where TLS < 1.3 (TLS 1.3 uses session tickets rather than
   1202          * application session caches).
   1203          *
   1204          * <p/>Looks up the session by ID in the application's session cache. If a valid session
   1205          * is returned, this callback is responsible for incrementing the reference count (and any
   1206          * required synchronization).
   1207          *
   1208          * @param id the ID of the session to find.
   1209          * @return the cached session or {@code 0} if no session was found matching the given ID.
   1210          */
   1211         @SuppressWarnings("unused")
   1212         long serverSessionRequested(byte[] id);
   1213     }
   1214 
   1215     static native String SSL_CIPHER_get_kx_name(long cipherAddress);
   1216 
   1217     static native String[] get_cipher_names(String selection);
   1218 
   1219     static native byte[] get_ocsp_single_extension(
   1220             byte[] ocspResponse, String oid, long x509Ref, OpenSSLX509Certificate holder, long issuerX509Ref, OpenSSLX509Certificate holder2);
   1221 
   1222     /**
   1223      * Returns the starting address of the memory region referenced by the provided direct
   1224      * {@link Buffer} or {@code 0} if the provided buffer is not direct or if such access to direct
   1225      * buffers is not supported by the platform.
   1226      *
   1227      * <p>NOTE: This method ignores the buffer's current {@code position}.
   1228      */
   1229     static native long getDirectBufferAddress(Buffer buf);
   1230 
   1231     static native long SSL_BIO_new(long ssl, NativeSsl ssl_holder) throws SSLException;
   1232 
   1233     static native int SSL_get_error(long ssl, NativeSsl ssl_holder, int ret);
   1234 
   1235     static native void SSL_clear_error();
   1236 
   1237     static native int SSL_pending_readable_bytes(long ssl, NativeSsl ssl_holder);
   1238 
   1239     static native int SSL_pending_written_bytes_in_BIO(long bio);
   1240 
   1241     /**
   1242      * Returns the maximum overhead, in bytes, of sealing a record with SSL.
   1243      */
   1244     static native int SSL_max_seal_overhead(long ssl, NativeSsl ssl_holder);
   1245 
   1246     /**
   1247      * Enables ALPN for this TLS endpoint and sets the list of supported ALPN protocols in
   1248      * wire-format (length-prefixed 8-bit strings).
   1249      */
   1250     static native void setApplicationProtocols(
   1251             long ssl, NativeSsl ssl_holder, boolean client, byte[] protocols) throws IOException;
   1252 
   1253     /**
   1254      * Called for a server endpoint only. Enables ALPN and sets a BiFunction that will
   1255      * be called to delegate protocol selection to the application. Calling this method overrides
   1256      * {@link #setApplicationProtocols(long, NativeSsl, boolean, byte[])}.
   1257      */
   1258     static native void setApplicationProtocolSelector(
   1259             long ssl, NativeSsl ssl_holder, ApplicationProtocolSelectorAdapter selector) throws IOException;
   1260 
   1261     /**
   1262      * Returns the selected ALPN protocol. If the server did not select a
   1263      * protocol, {@code null} will be returned.
   1264      */
   1265     static native byte[] getApplicationProtocol(long ssl, NativeSsl ssl_holder);
   1266 
   1267     /**
   1268      * Variant of the {@link #SSL_do_handshake} used by {@link ConscryptEngine}. This differs
   1269      * slightly from the raw BoringSSL API in that it returns the SSL error code from the
   1270      * operation, rather than the return value from {@code SSL_do_handshake}. This is done in
   1271      * order to allow to properly handle SSL errors and propagate useful exceptions.
   1272      *
   1273      * @return Returns the SSL error code for the operation when the error was {@code
   1274      * SSL_ERROR_NONE}, {@code SSL_ERROR_WANT_READ}, or {@code SSL_ERROR_WANT_WRITE}.
   1275      * @throws IOException when the error code is anything except those returned by this method.
   1276      */
   1277     static native int ENGINE_SSL_do_handshake(long ssl, NativeSsl ssl_holder, SSLHandshakeCallbacks shc)
   1278             throws IOException;
   1279 
   1280     /**
   1281      * Variant of the {@link #SSL_read} for a direct {@link java.nio.ByteBuffer} used by {@link
   1282      * ConscryptEngine}.
   1283      *
   1284      * @return if positive, represents the number of bytes read into the given buffer.
   1285      * Returns {@code -SSL_ERROR_WANT_READ} if more data is needed. Returns
   1286      * {@code -SSL_ERROR_WANT_WRITE} if data needs to be written out to flush the BIO.
   1287      *
   1288      * @throws java.io.InterruptedIOException if the read was interrupted.
   1289      * @throws java.io.EOFException if the end of stream has been reached.
   1290      * @throws CertificateException if the application's certificate verification callback failed.
   1291      * Only occurs during handshake processing.
   1292      * @throws SSLException if any other error occurs.
   1293      */
   1294     static native int ENGINE_SSL_read_direct(long ssl, NativeSsl ssl_holder, long address, int length,
   1295             SSLHandshakeCallbacks shc) throws IOException, CertificateException;
   1296 
   1297     /**
   1298      * Variant of the {@link #SSL_write} for a direct {@link java.nio.ByteBuffer} used by {@link
   1299      * ConscryptEngine}. This version does not lock or and does no error pre-processing.
   1300      */
   1301     static native int ENGINE_SSL_write_direct(long ssl, NativeSsl ssl_holder, long address, int length,
   1302             SSLHandshakeCallbacks shc) throws IOException;
   1303 
   1304     /**
   1305      * Writes data from the given direct {@link java.nio.ByteBuffer} to the BIO.
   1306      */
   1307     static native int ENGINE_SSL_write_BIO_direct(long ssl, NativeSsl ssl_holder, long bioRef, long pos, int length,
   1308             SSLHandshakeCallbacks shc) throws IOException;
   1309 
   1310     /**
   1311      * Writes data from the given array to the BIO.
   1312      */
   1313     static native int ENGINE_SSL_write_BIO_heap(long ssl, NativeSsl ssl_holder, long bioRef, byte[] sourceJava,
   1314             int sourceOffset, int sourceLength, SSLHandshakeCallbacks shc)
   1315             throws IOException, IndexOutOfBoundsException;
   1316 
   1317     /**
   1318      * Reads data from the given BIO into a direct {@link java.nio.ByteBuffer}.
   1319      */
   1320     static native int ENGINE_SSL_read_BIO_direct(long ssl, NativeSsl ssl_holder, long bioRef, long address, int len,
   1321             SSLHandshakeCallbacks shc) throws IOException;
   1322 
   1323     /**
   1324      * Reads data from the given BIO into an array.
   1325      */
   1326     static native int ENGINE_SSL_read_BIO_heap(long ssl, NativeSsl ssl_holder, long bioRef, byte[] destJava,
   1327             int destOffset, int destLength, SSLHandshakeCallbacks shc)
   1328             throws IOException, IndexOutOfBoundsException;
   1329 
   1330     /**
   1331      * Variant of the {@link #SSL_shutdown} used by {@link ConscryptEngine}. This version does not
   1332      * lock.
   1333      */
   1334     static native void ENGINE_SSL_shutdown(long ssl, NativeSsl ssl_holder, SSLHandshakeCallbacks shc)
   1335             throws IOException;
   1336 
   1337     /**
   1338      * Used for testing only.
   1339      */
   1340     static native int BIO_read(long bioRef, byte[] buffer) throws IOException;
   1341     static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
   1342             throws IOException, IndexOutOfBoundsException;
   1343     static native long ERR_peek_last_error();
   1344     static native long SSL_clear_mode(long ssl, NativeSsl ssl_holder, long mode);
   1345     static native long SSL_get_mode(long ssl, NativeSsl ssl_holder);
   1346     static native long SSL_get_options(long ssl, NativeSsl ssl_holder);
   1347     static native long SSL_get1_session(long ssl, NativeSsl ssl_holder);
   1348 }
   1349