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.security.MessageDigest;
     24 import java.security.NoSuchAlgorithmException;
     25 import java.security.SignatureException;
     26 import java.security.cert.Certificate;
     27 import java.security.cert.CertificateEncodingException;
     28 import java.security.cert.CertificateException;
     29 import java.security.cert.CertificateParsingException;
     30 import java.util.ArrayList;
     31 import java.util.Calendar;
     32 import java.util.HashMap;
     33 import java.util.LinkedHashMap;
     34 import java.util.List;
     35 import java.util.Map;
     36 import javax.crypto.BadPaddingException;
     37 import javax.crypto.IllegalBlockSizeException;
     38 import javax.net.ssl.SSLException;
     39 import javax.security.auth.x500.X500Principal;
     40 
     41 /**
     42  * Provides the Java side of our JNI glue for OpenSSL.
     43  */
     44 public final class NativeCrypto {
     45 
     46     // --- OpenSSL library initialization --------------------------------------
     47     static {
     48         /*
     49          * If we're compiled as part of Android, should use a different JNI
     50          * library name. Detect this by looking for the jarjar'd package name.
     51          */
     52         if ("com.android.org.conscrypt".equals(NativeCrypto.class.getPackage().getName())) {
     53             System.loadLibrary("javacrypto");
     54         } else {
     55             System.loadLibrary("conscrypt_jni");
     56         }
     57 
     58         clinit();
     59     }
     60 
     61     private native static void clinit();
     62 
     63     // --- ENGINE functions ----------------------------------------------------
     64     public static native void ENGINE_load_dynamic();
     65 
     66     public static native long ENGINE_by_id(String id);
     67 
     68     public static native int ENGINE_add(long e);
     69 
     70     public static native int ENGINE_init(long e);
     71 
     72     public static native int ENGINE_finish(long e);
     73 
     74     public static native int ENGINE_free(long e);
     75 
     76     public static native long ENGINE_load_private_key(long e, String key_id);
     77 
     78     public static native String ENGINE_get_id(long engineRef);
     79 
     80     public static native int ENGINE_ctrl_cmd_string(long engineRef, String cmd, String arg,
     81             int cmd_optional);
     82 
     83     // --- DSA/RSA public/private key handling functions -----------------------
     84 
     85     public static native long EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
     86                                                byte[] pub_key, byte[] priv_key);
     87 
     88     public static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
     89             byte[] dmp1, byte[] dmq1, byte[] iqmp);
     90 
     91     public static native long EVP_PKEY_new_mac_key(int type, byte[] key);
     92 
     93     public static native int EVP_PKEY_size(long pkey);
     94 
     95     public static native int EVP_PKEY_type(long pkey);
     96 
     97     public static native String EVP_PKEY_print_public(long pkeyRef);
     98 
     99     public static native String EVP_PKEY_print_private(long pkeyRef);
    100 
    101     public static native void EVP_PKEY_free(long pkey);
    102 
    103     public static native int EVP_PKEY_cmp(long pkey1, long pkey2);
    104 
    105     public static native byte[] i2d_PKCS8_PRIV_KEY_INFO(long pkey);
    106 
    107     public static native long d2i_PKCS8_PRIV_KEY_INFO(byte[] data);
    108 
    109     public static native byte[] i2d_PUBKEY(long pkey);
    110 
    111     public static native long d2i_PUBKEY(byte[] data);
    112 
    113     public static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
    114 
    115     public static native int RSA_size(long pkey);
    116 
    117     public static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, long pkey,
    118             int padding);
    119 
    120     public static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, long pkey,
    121             int padding) throws BadPaddingException, SignatureException;
    122 
    123     public static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, long pkey,
    124             int padding);
    125 
    126     public static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, long pkey,
    127             int padding) throws BadPaddingException, SignatureException;
    128 
    129     /**
    130      * @return array of {n, e}
    131      */
    132     public static native byte[][] get_RSA_public_params(long rsa);
    133 
    134     /**
    135      * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
    136      */
    137     public static native byte[][] get_RSA_private_params(long rsa);
    138 
    139     public static native long DSA_generate_key(int primeBits, byte[] seed, byte[] g, byte[] p,
    140             byte[] q);
    141 
    142     /**
    143      * @return array of {g, p, q, y(pub), x(priv)}
    144      */
    145     public static native byte[][] get_DSA_params(long dsa);
    146 
    147     public static native byte[] i2d_RSAPublicKey(long rsa);
    148 
    149     public static native byte[] i2d_RSAPrivateKey(long rsa);
    150 
    151     public static native byte[] i2d_DSAPublicKey(long dsa);
    152 
    153     public static native byte[] i2d_DSAPrivateKey(long dsa);
    154 
    155     // --- EC functions --------------------------
    156 
    157     /**
    158      * Used to request EC_GROUP_new_curve_GFp to EC_GROUP_new_curve
    159      */
    160     public static final int EC_CURVE_GFP = 1;
    161 
    162     /**
    163      * Used to request EC_GROUP_new_curve_GF2m to EC_GROUP_new_curve
    164      */
    165     public static final int EC_CURVE_GF2M = 2;
    166 
    167     /**
    168      * EC_GROUP_set_asn1_flag: indicates an EC_GROUP is a NamedCurve.
    169      */
    170     public static final int OPENSSL_EC_NAMED_CURVE = 0x001;
    171 
    172     /**
    173      * EC_GROUP_set_point_conversion_form: indicates compressed ASN.1 format
    174      */
    175     public static final int POINT_CONVERSION_COMPRESSED = 2;
    176 
    177     /**
    178      * EC_GROUP_set_point_conversion_form: indicates uncompressed ASN.1 format
    179      */
    180     public static final int POINT_CONVERSION_UNCOMPRESSED = 4;
    181 
    182     /**
    183      * EC_GROUP_set_point_conversion_form: indicates hybrid ASN.1 format
    184      */
    185     public static final int POINT_CONVERSION_HYBRID = 4;
    186 
    187     public static native long EVP_PKEY_new_EC_KEY(long groupRef, long pubkeyRef, byte[] privkey);
    188 
    189     public static native long EC_GROUP_new_by_curve_name(String curveName);
    190 
    191     public static native long EC_GROUP_new_curve(int type, byte[] p, byte[] a, byte[] b);
    192 
    193     public static native long EC_GROUP_dup(long groupRef);
    194 
    195     public static native void EC_GROUP_set_asn1_flag(long groupRef, int flag);
    196 
    197     public static native void EC_GROUP_set_point_conversion_form(long groupRef, int form);
    198 
    199     public static native String EC_GROUP_get_curve_name(long groupRef);
    200 
    201     public static native byte[][] EC_GROUP_get_curve(long groupRef);
    202 
    203     public static native void EC_GROUP_clear_free(long ctx);
    204 
    205     public static native boolean EC_GROUP_cmp(long ctx1, long ctx2);
    206 
    207     public static native void EC_GROUP_set_generator(long groupCtx, long pointCtx, byte[] n, byte[] h);
    208 
    209     public static native long EC_GROUP_get_generator(long groupCtx);
    210 
    211     public static native int get_EC_GROUP_type(long groupCtx);
    212 
    213     public static native byte[] EC_GROUP_get_order(long groupCtx);
    214 
    215     public static native int EC_GROUP_get_degree(long groupCtx);
    216 
    217     public static native byte[] EC_GROUP_get_cofactor(long groupCtx);
    218 
    219     public static native long EC_POINT_new(long groupRef);
    220 
    221     public static native void EC_POINT_clear_free(long pointRef);
    222 
    223     public static native boolean EC_POINT_cmp(long groupRef, long pointRef1, long pointRef2);
    224 
    225     public static native byte[][] EC_POINT_get_affine_coordinates(long groupCtx, long pointCtx);
    226 
    227     public static native void EC_POINT_set_affine_coordinates(long groupCtx, long pointCtx, byte[] x,
    228             byte[] y);
    229 
    230     public static native long EC_KEY_generate_key(long groupRef);
    231 
    232     public static native long EC_KEY_get0_group(long pkeyRef);
    233 
    234     public static native byte[] EC_KEY_get_private_key(long keyRef);
    235 
    236     public static native long EC_KEY_get_public_key(long keyRef);
    237 
    238     public static native int ECDH_compute_key(
    239             byte[] out, int outOffset, long publicKeyRef, long privateKeyRef);
    240 
    241     // --- Message digest functions --------------
    242 
    243     public static native long EVP_get_digestbyname(String name);
    244 
    245     public static native int EVP_MD_size(long evp_md);
    246 
    247     public static native int EVP_MD_block_size(long evp_md);
    248 
    249     // --- Message digest context functions --------------
    250 
    251     public static native long EVP_MD_CTX_create();
    252 
    253     public static native void EVP_MD_CTX_init(long ctx);
    254 
    255     public static native void EVP_MD_CTX_destroy(long ctx);
    256 
    257     public static native long EVP_MD_CTX_copy(long ctx);
    258 
    259     // --- Digest handling functions -------------------------------------------
    260 
    261     public static native long EVP_DigestInit(long evp_md);
    262 
    263     public static native void EVP_DigestUpdate(long ctx, byte[] buffer, int offset, int length);
    264 
    265     public static native int EVP_DigestFinal(long ctx, byte[] hash, int offset);
    266 
    267     // --- MAC handling functions ----------------------------------------------
    268 
    269     public static native void EVP_DigestSignInit(long evp_md_ctx, long evp_md, long evp_pkey);
    270 
    271     public static native void EVP_DigestSignUpdate(long evp_md_ctx, byte[] in);
    272 
    273     public static native byte[] EVP_DigestSignFinal(long evp_md_ctx);
    274 
    275     // --- Signature handling functions ----------------------------------------
    276 
    277     public static native long EVP_SignInit(String algorithm);
    278 
    279     public static native void EVP_SignUpdate(long ctx, byte[] buffer,
    280                                                int offset, int length);
    281 
    282     public static native int EVP_SignFinal(long ctx, byte[] signature, int offset, long key);
    283 
    284     public static native long EVP_VerifyInit(String algorithm);
    285 
    286     public static native void EVP_VerifyUpdate(long ctx, byte[] buffer,
    287                                                int offset, int length);
    288 
    289     public static native int EVP_VerifyFinal(long ctx, byte[] signature,
    290                                              int offset, int length, long key);
    291 
    292 
    293     // --- Block ciphers -------------------------------------------------------
    294 
    295     public static native long EVP_get_cipherbyname(String string);
    296 
    297     public static native void EVP_CipherInit_ex(long ctx, long evpCipher, byte[] key, byte[] iv,
    298             boolean encrypting);
    299 
    300     public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
    301             int inOffset, int inLength);
    302 
    303     public static native int EVP_CipherFinal_ex(long ctx, byte[] out, int outOffset)
    304             throws BadPaddingException, IllegalBlockSizeException;
    305 
    306     public static native int EVP_CIPHER_iv_length(long evpCipher);
    307 
    308     public static native long EVP_CIPHER_CTX_new();
    309 
    310     public static native int EVP_CIPHER_CTX_block_size(long ctx);
    311 
    312     public static native int get_EVP_CIPHER_CTX_buf_len(long ctx);
    313 
    314     public static native void EVP_CIPHER_CTX_set_padding(long ctx, boolean enablePadding);
    315 
    316     public static native void EVP_CIPHER_CTX_set_key_length(long ctx, int keyBitSize);
    317 
    318     public static native void EVP_CIPHER_CTX_cleanup(long ctx);
    319 
    320     // --- RAND seeding --------------------------------------------------------
    321 
    322     public static final int RAND_SEED_LENGTH_IN_BYTES = 1024;
    323 
    324     public static native void RAND_seed(byte[] seed);
    325 
    326     public static native int RAND_load_file(String filename, long max_bytes);
    327 
    328     public static native void RAND_bytes(byte[] output);
    329 
    330     // --- ASN.1 objects -------------------------------------------------------
    331 
    332     public static native int OBJ_txt2nid(String oid);
    333 
    334     public static native String OBJ_txt2nid_longName(String oid);
    335 
    336     public static native String OBJ_txt2nid_oid(String oid);
    337 
    338     // --- X509_NAME -----------------------------------------------------------
    339 
    340     public static int X509_NAME_hash(X500Principal principal) {
    341         return X509_NAME_hash(principal, "SHA1");
    342     }
    343     public static int X509_NAME_hash_old(X500Principal principal) {
    344         return X509_NAME_hash(principal, "MD5");
    345     }
    346     private static int X509_NAME_hash(X500Principal principal, String algorithm) {
    347         try {
    348             byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
    349             int offset = 0;
    350             return (((digest[offset++] & 0xff) <<  0) |
    351                     ((digest[offset++] & 0xff) <<  8) |
    352                     ((digest[offset++] & 0xff) << 16) |
    353                     ((digest[offset  ] & 0xff) << 24));
    354         } catch (NoSuchAlgorithmException e) {
    355             throw new AssertionError(e);
    356         }
    357     }
    358 
    359     public static native String X509_NAME_print_ex(long x509nameCtx, long flags);
    360 
    361     // --- X509 ----------------------------------------------------------------
    362 
    363     /** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
    364     public static final int GN_STACK_SUBJECT_ALT_NAME = 1;
    365 
    366     /**
    367      * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
    368      * extension.
    369      */
    370     public static final int GN_STACK_ISSUER_ALT_NAME = 2;
    371 
    372     /**
    373      * Used to request only non-critical types in get_X509*_ext_oids.
    374      */
    375     public static final int EXTENSION_TYPE_NON_CRITICAL = 0;
    376 
    377     /**
    378      * Used to request only critical types in get_X509*_ext_oids.
    379      */
    380     public static final int EXTENSION_TYPE_CRITICAL = 1;
    381 
    382     public static native long d2i_X509_bio(long bioCtx);
    383 
    384     public static native long d2i_X509(byte[] encoded);
    385 
    386     public static native long PEM_read_bio_X509(long bioCtx);
    387 
    388     public static native byte[] i2d_X509(long x509ctx);
    389 
    390     /** Takes an X509 context not an X509_PUBKEY context. */
    391     public static native byte[] i2d_X509_PUBKEY(long x509ctx);
    392 
    393     public static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
    394 
    395     public static native long[] ASN1_seq_unpack_X509_bio(long bioRef);
    396 
    397     public static native void X509_free(long x509ctx);
    398 
    399     public static native int X509_cmp(long x509ctx1, long x509ctx2);
    400 
    401     public static native int get_X509_hashCode(long x509ctx);
    402 
    403     public static native void X509_print_ex(long bioCtx, long x509ctx, long nmflag, long certflag);
    404 
    405     public static native byte[] X509_get_issuer_name(long x509ctx);
    406 
    407     public static native byte[] X509_get_subject_name(long x509ctx);
    408 
    409     public static native String get_X509_sig_alg_oid(long x509ctx);
    410 
    411     public static native byte[] get_X509_sig_alg_parameter(long x509ctx);
    412 
    413     public static native boolean[] get_X509_issuerUID(long x509ctx);
    414 
    415     public static native boolean[] get_X509_subjectUID(long x509ctx);
    416 
    417     public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException;
    418 
    419     public static native String get_X509_pubkey_oid(long x509ctx);
    420 
    421     public static native byte[] X509_get_ext_oid(long x509ctx, String oid);
    422 
    423     public static native String[] get_X509_ext_oids(long x509ctx, int critical);
    424 
    425     public static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, int type)
    426             throws CertificateParsingException;
    427 
    428     public static native boolean[] get_X509_ex_kusage(long x509ctx);
    429 
    430     public static native String[] get_X509_ex_xkusage(long x509ctx);
    431 
    432     public static native int get_X509_ex_pathlen(long x509ctx);
    433 
    434     public static native long X509_get_notBefore(long x509ctx);
    435 
    436     public static native long X509_get_notAfter(long x509ctx);
    437 
    438     public static native long X509_get_version(long x509ctx);
    439 
    440     public static native byte[] X509_get_serialNumber(long x509ctx);
    441 
    442     public static native void X509_verify(long x509ctx, long pkeyCtx);
    443 
    444     public static native byte[] get_X509_cert_info_enc(long x509ctx);
    445 
    446     public static native byte[] get_X509_signature(long x509ctx);
    447 
    448     public static native int get_X509_ex_flags(long x509ctx);
    449 
    450     public static native int X509_check_issued(long ctx, long ctx2);
    451 
    452     // --- X509 EXFLAG ---------------------------------------------------------
    453 
    454     public static final int EXFLAG_CA = 0x10;
    455 
    456     public static final int EXFLAG_CRITICAL = 0x200;
    457 
    458     // --- PKCS7 ---------------------------------------------------------------
    459 
    460     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    461     public static final int PKCS7_CERTS = 1;
    462 
    463     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    464     public static final int PKCS7_CRLS = 2;
    465 
    466     /** Returns an array of X509 or X509_CRL pointers. */
    467     public static native long[] d2i_PKCS7_bio(long bioCtx, int which);
    468 
    469     /** Returns an array of X509 or X509_CRL pointers. */
    470     public static native byte[] i2d_PKCS7(long[] certs);
    471 
    472     /** Returns an array of X509 or X509_CRL pointers. */
    473     public static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
    474 
    475     // --- X509_CRL ------------------------------------------------------------
    476 
    477     public static native long d2i_X509_CRL_bio(long bioCtx);
    478 
    479     public static native long PEM_read_bio_X509_CRL(long bioCtx);
    480 
    481     public static native byte[] i2d_X509_CRL(long x509CrlCtx);
    482 
    483     public static native void X509_CRL_free(long x509CrlCtx);
    484 
    485     public static native void X509_CRL_print(long bioCtx, long x509CrlCtx);
    486 
    487     public static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx);
    488 
    489     public static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx);
    490 
    491     public static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx);
    492 
    493     /** Returns X509_REVOKED reference that is not duplicated! */
    494     public static native long X509_CRL_get0_by_cert(long x509CrlCtx, long x509Ctx);
    495 
    496     /** Returns X509_REVOKED reference that is not duplicated! */
    497     public static native long X509_CRL_get0_by_serial(long x509CrlCtx, byte[] serial);
    498 
    499     /** Returns an array of X509_REVOKED that are owned by the caller. */
    500     public static native long[] X509_CRL_get_REVOKED(long x509CrlCtx);
    501 
    502     public static native String[] get_X509_CRL_ext_oids(long x509ctx, int critical);
    503 
    504     public static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, String oid);
    505 
    506     public static native long X509_CRL_get_version(long x509CrlCtx);
    507 
    508     public static native long X509_CRL_get_ext(long x509CrlCtx, String oid);
    509 
    510     public static native byte[] get_X509_CRL_signature(long x509ctx);
    511 
    512     public static native void X509_CRL_verify(long x509CrlCtx, long pkeyCtx);
    513 
    514     public static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx);
    515 
    516     public static native long X509_CRL_get_lastUpdate(long x509CrlCtx);
    517 
    518     public static native long X509_CRL_get_nextUpdate(long x509CrlCtx);
    519 
    520     // --- X509_REVOKED --------------------------------------------------------
    521 
    522     public static native long X509_REVOKED_dup(long x509RevokedCtx);
    523 
    524     public static native byte[] i2d_X509_REVOKED(long x509RevokedCtx);
    525 
    526     public static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical);
    527 
    528     public static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid);
    529 
    530     public static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx);
    531 
    532     public static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid);
    533 
    534     /** Returns ASN1_TIME reference. */
    535     public static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx);
    536 
    537     public static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx);
    538 
    539     // --- X509_EXTENSION ------------------------------------------------------
    540 
    541     public static native int X509_supported_extension(long x509ExtensionRef);
    542 
    543     // --- ASN1_TIME -----------------------------------------------------------
    544 
    545     public static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal);
    546 
    547     // --- BIO stream creation -------------------------------------------------
    548 
    549     public static native long create_BIO_InputStream(OpenSSLBIOInputStream is);
    550 
    551     public static native long create_BIO_OutputStream(OutputStream os);
    552 
    553     public static native int BIO_read(long bioRef, byte[] buffer);
    554 
    555     public static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
    556             throws IOException;
    557 
    558     public static native void BIO_free(long bioRef);
    559 
    560     // --- SSL handling --------------------------------------------------------
    561 
    562     private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
    563     private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
    564     private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
    565     private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
    566 
    567     public static final Map<String, String> OPENSSL_TO_STANDARD_CIPHER_SUITES
    568             = new HashMap<String, String>();
    569     public static final Map<String, String> STANDARD_TO_OPENSSL_CIPHER_SUITES
    570             = new LinkedHashMap<String, String>();
    571 
    572     private static void add(String standard, String openssl) {
    573         OPENSSL_TO_STANDARD_CIPHER_SUITES.put(openssl, standard);
    574         STANDARD_TO_OPENSSL_CIPHER_SUITES.put(standard, openssl);
    575     }
    576 
    577     /**
    578      * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
    579      * indication signaling cipher suite value. It is not a real
    580      * cipher suite. It is just an indication in the default and
    581      * supported cipher suite lists indicates that the implementation
    582      * supports secure renegotiation.
    583      *
    584      * In the RI, its presence means that the SCSV is sent in the
    585      * cipher suite list to indicate secure renegotiation support and
    586      * its absense means to send an empty TLS renegotiation info
    587      * extension instead.
    588      *
    589      * However, OpenSSL doesn't provide an API to give this level of
    590      * control, instead always sending the SCSV and always including
    591      * the empty renegotiation info if TLS is used (as opposed to
    592      * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
    593      * be passed for compatibility as to provide the hint that we
    594      * support secure renegotiation.
    595      */
    596     public static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV
    597             = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
    598 
    599     static {
    600         // Note these are added in priority order
    601         add("SSL_RSA_WITH_RC4_128_MD5",              "RC4-MD5");
    602         add("SSL_RSA_WITH_RC4_128_SHA",              "RC4-SHA");
    603         add("TLS_RSA_WITH_AES_128_CBC_SHA",          "AES128-SHA");
    604         add("TLS_RSA_WITH_AES_256_CBC_SHA",          "AES256-SHA");
    605         add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",       "ECDH-ECDSA-RC4-SHA");
    606         add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",   "ECDH-ECDSA-AES128-SHA");
    607         add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",   "ECDH-ECDSA-AES256-SHA");
    608         add("TLS_ECDH_RSA_WITH_RC4_128_SHA",         "ECDH-RSA-RC4-SHA");
    609         add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",     "ECDH-RSA-AES128-SHA");
    610         add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",     "ECDH-RSA-AES256-SHA");
    611         add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",      "ECDHE-ECDSA-RC4-SHA");
    612         add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",  "ECDHE-ECDSA-AES128-SHA");
    613         add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",  "ECDHE-ECDSA-AES256-SHA");
    614         add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",        "ECDHE-RSA-RC4-SHA");
    615         add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",    "ECDHE-RSA-AES128-SHA");
    616         add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",    "ECDHE-RSA-AES256-SHA");
    617         add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",      "DHE-RSA-AES128-SHA");
    618         add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA",      "DHE-RSA-AES256-SHA");
    619         add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",      "DHE-DSS-AES128-SHA");
    620         add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA",      "DHE-DSS-AES256-SHA");
    621         add("SSL_RSA_WITH_3DES_EDE_CBC_SHA",         "DES-CBC3-SHA");
    622         add("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",  "ECDH-ECDSA-DES-CBC3-SHA");
    623         add("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",    "ECDH-RSA-DES-CBC3-SHA");
    624         add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "ECDHE-ECDSA-DES-CBC3-SHA");
    625         add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",   "ECDHE-RSA-DES-CBC3-SHA");
    626         add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",     "EDH-RSA-DES-CBC3-SHA");
    627         add("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",     "EDH-DSS-DES-CBC3-SHA");
    628         add("SSL_RSA_WITH_DES_CBC_SHA",              "DES-CBC-SHA");
    629         add("SSL_DHE_RSA_WITH_DES_CBC_SHA",          "EDH-RSA-DES-CBC-SHA");
    630         add("SSL_DHE_DSS_WITH_DES_CBC_SHA",          "EDH-DSS-DES-CBC-SHA");
    631         add("SSL_RSA_EXPORT_WITH_RC4_40_MD5",        "EXP-RC4-MD5");
    632         add("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",     "EXP-DES-CBC-SHA");
    633         add("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-RSA-DES-CBC-SHA");
    634         add("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-DSS-DES-CBC-SHA");
    635         add("SSL_RSA_WITH_NULL_MD5",                 "NULL-MD5");
    636         add("SSL_RSA_WITH_NULL_SHA",                 "NULL-SHA");
    637         add("TLS_ECDH_ECDSA_WITH_NULL_SHA",          "ECDH-ECDSA-NULL-SHA");
    638         add("TLS_ECDH_RSA_WITH_NULL_SHA",            "ECDH-RSA-NULL-SHA");
    639         add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",         "ECDHE-ECDSA-NULL-SHA");
    640         add("TLS_ECDHE_RSA_WITH_NULL_SHA",           "ECDHE-RSA-NULL-SHA");
    641         add("SSL_DH_anon_WITH_RC4_128_MD5",          "ADH-RC4-MD5");
    642         add("TLS_DH_anon_WITH_AES_128_CBC_SHA",      "ADH-AES128-SHA");
    643         add("TLS_DH_anon_WITH_AES_256_CBC_SHA",      "ADH-AES256-SHA");
    644         add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",     "ADH-DES-CBC3-SHA");
    645         add("SSL_DH_anon_WITH_DES_CBC_SHA",          "ADH-DES-CBC-SHA");
    646         add("TLS_ECDH_anon_WITH_RC4_128_SHA",        "AECDH-RC4-SHA");
    647         add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",    "AECDH-AES128-SHA");
    648         add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",    "AECDH-AES256-SHA");
    649         add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",   "AECDH-DES-CBC3-SHA");
    650         add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",    "EXP-ADH-RC4-MD5");
    651         add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", "EXP-ADH-DES-CBC-SHA");
    652         add("TLS_ECDH_anon_WITH_NULL_SHA",           "AECDH-NULL-SHA");
    653 
    654         // No Kerberos in Android
    655         // add("TLS_KRB5_WITH_RC4_128_SHA",           "KRB5-RC4-SHA");
    656         // add("TLS_KRB5_WITH_RC4_128_MD5",           "KRB5-RC4-MD5");
    657         // add("TLS_KRB5_WITH_3DES_EDE_CBC_SHA",      "KRB5-DES-CBC3-SHA");
    658         // add("TLS_KRB5_WITH_3DES_EDE_CBC_MD5",      "KRB5-DES-CBC3-MD5");
    659         // add("TLS_KRB5_WITH_DES_CBC_SHA",           "KRB5-DES-CBC-SHA");
    660         // add("TLS_KRB5_WITH_DES_CBC_MD5",           "KRB5-DES-CBC-MD5");
    661         // add("TLS_KRB5_EXPORT_WITH_RC4_40_SHA",     "EXP-KRB5-RC4-SHA");
    662         // add("TLS_KRB5_EXPORT_WITH_RC4_40_MD5",     "EXP-KRB5-RC4-MD5");
    663         // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", "EXP-KRB5-DES-CBC-SHA");
    664         // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", "EXP-KRB5-DES-CBC-MD5");
    665 
    666         // not implemented by either RI or OpenSSL
    667         // add("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", null);
    668         // add("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", null);
    669 
    670         // EXPORT1024 suites were never standardized but were widely implemented.
    671         // OpenSSL 0.9.8c and later have disabled TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES
    672         // add("SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA", "EXP1024-DES-CBC-SHA");
    673         // add("SSL_RSA_EXPORT1024_WITH_RC4_56_SHA",  "EXP1024-RC4-SHA");
    674 
    675         // No RC2
    676         // add("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5",  "EXP-RC2-CBC-MD5");
    677         // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", "EXP-KRB5-RC2-CBC-SHA");
    678         // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", "EXP-KRB5-RC2-CBC-MD5");
    679 
    680         // PSK is Private Shared Key - didn't exist in Froyo's openssl - no JSSE equivalent
    681         // add(null, "PSK-3DES-EDE-CBC-SHA");
    682         // add(null, "PSK-AES128-CBC-SHA");
    683         // add(null, "PSK-AES256-CBC-SHA");
    684         // add(null, "PSK-RC4-SHA");
    685 
    686         // Signaling Cipher Suite Value for secure renegotiation handled as special case.
    687         // add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", null);
    688     }
    689 
    690     private static final String[] SUPPORTED_CIPHER_SUITES;
    691     static {
    692         int size = STANDARD_TO_OPENSSL_CIPHER_SUITES.size();
    693         SUPPORTED_CIPHER_SUITES = new String[size + 1];
    694         STANDARD_TO_OPENSSL_CIPHER_SUITES.keySet().toArray(SUPPORTED_CIPHER_SUITES);
    695         SUPPORTED_CIPHER_SUITES[size] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
    696     }
    697 
    698     // EVP_PKEY types from evp.h and objects.h
    699     public static final int EVP_PKEY_RSA  = 6;   // NID_rsaEcnryption
    700     public static final int EVP_PKEY_DSA  = 116; // NID_dsa
    701     public static final int EVP_PKEY_DH   = 28;  // NID_dhKeyAgreement
    702     public static final int EVP_PKEY_EC   = 408; // NID_X9_62_id_ecPublicKey
    703     public static final int EVP_PKEY_HMAC = 855; // NID_hmac
    704     public static final int EVP_PKEY_CMAC = 894; // NID_cmac
    705 
    706     // RSA padding modes from rsa.h
    707     public static final int RSA_PKCS1_PADDING = 1;
    708     public static final int RSA_NO_PADDING    = 3;
    709 
    710     // SSL mode from ssl.h
    711     public static final long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000020L;
    712 
    713     // SSL options from ssl.h
    714     public static final long SSL_OP_NO_TICKET                              = 0x00004000L;
    715     public static final long SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 0x00010000L;
    716     public static final long SSL_OP_NO_SSLv3                               = 0x02000000L;
    717     public static final long SSL_OP_NO_TLSv1                               = 0x04000000L;
    718     public static final long SSL_OP_NO_TLSv1_1                             = 0x10000000L;
    719     public static final long SSL_OP_NO_TLSv1_2                             = 0x08000000L;
    720 
    721     public static native long SSL_CTX_new();
    722 
    723     public static String[] getDefaultCipherSuites() {
    724         return new String[] {
    725             "SSL_RSA_WITH_RC4_128_MD5",
    726             "SSL_RSA_WITH_RC4_128_SHA",
    727             "TLS_RSA_WITH_AES_128_CBC_SHA",
    728             "TLS_RSA_WITH_AES_256_CBC_SHA",
    729             "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
    730             "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
    731             "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
    732             "TLS_ECDH_RSA_WITH_RC4_128_SHA",
    733             "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
    734             "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
    735             "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
    736             "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
    737             "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
    738             "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
    739             "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
    740             "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
    741             "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
    742             "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
    743             "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
    744             "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
    745             "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
    746             "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
    747             "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
    748             "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
    749             "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
    750             "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
    751             "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
    752             "SSL_RSA_WITH_DES_CBC_SHA",
    753             "SSL_DHE_RSA_WITH_DES_CBC_SHA",
    754             "SSL_DHE_DSS_WITH_DES_CBC_SHA",
    755             "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
    756             "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
    757             "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
    758             "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
    759             TLS_EMPTY_RENEGOTIATION_INFO_SCSV
    760         };
    761     }
    762 
    763     public static String[] getSupportedCipherSuites() {
    764         return SUPPORTED_CIPHER_SUITES.clone();
    765     }
    766 
    767     public static native void SSL_CTX_free(long ssl_ctx);
    768 
    769     public static native void SSL_CTX_set_session_id_context(long ssl_ctx, byte[] sid_ctx);
    770 
    771     public static native long SSL_new(long ssl_ctx) throws SSLException;
    772 
    773     public static native void SSL_enable_tls_channel_id(long ssl) throws SSLException;
    774 
    775     public static native byte[] SSL_get_tls_channel_id(long ssl) throws SSLException;
    776 
    777     public static native void SSL_set1_tls_channel_id(long ssl, long pkey);
    778 
    779     public static byte[][] encodeCertificates(Certificate[] certificates)
    780             throws CertificateEncodingException {
    781         byte[][] certificateBytes = new byte[certificates.length][];
    782         for (int i = 0; i < certificates.length; i++) {
    783             certificateBytes[i] = certificates[i].getEncoded();
    784         }
    785         return certificateBytes;
    786     }
    787 
    788     public static native void SSL_use_certificate(long ssl, byte[][] asn1DerEncodedCertificateChain);
    789 
    790     public static native void SSL_use_PrivateKey(long ssl, long pkey);
    791 
    792     public static native void SSL_check_private_key(long ssl) throws SSLException;
    793 
    794     public static native void SSL_set_client_CA_list(long ssl, byte[][] asn1DerEncodedX500Principals);
    795 
    796     public static native long SSL_get_mode(long ssl);
    797 
    798     public static native long SSL_set_mode(long ssl, long mode);
    799 
    800     public static native long SSL_clear_mode(long ssl, long mode);
    801 
    802     public static native long SSL_get_options(long ssl);
    803 
    804     public static native long SSL_set_options(long ssl, long options);
    805 
    806     public static native long SSL_clear_options(long ssl, long options);
    807 
    808     public static String[] getDefaultProtocols() {
    809         return new String[] { SUPPORTED_PROTOCOL_SSLV3,
    810                               SUPPORTED_PROTOCOL_TLSV1,
    811         };
    812     }
    813 
    814     public static String[] getSupportedProtocols() {
    815         return new String[] { SUPPORTED_PROTOCOL_SSLV3,
    816                               SUPPORTED_PROTOCOL_TLSV1,
    817                               SUPPORTED_PROTOCOL_TLSV1_1,
    818                               SUPPORTED_PROTOCOL_TLSV1_2,
    819         };
    820     }
    821 
    822     public static void setEnabledProtocols(long ssl, String[] protocols) {
    823         checkEnabledProtocols(protocols);
    824         // openssl uses negative logic letting you disable protocols.
    825         // so first, assume we need to set all (disable all) and clear none (enable none).
    826         // in the loop, selectively move bits from set to clear (from disable to enable)
    827         long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
    828         long optionsToClear = 0;
    829         for (int i = 0; i < protocols.length; i++) {
    830             String protocol = protocols[i];
    831             if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
    832                 optionsToSet &= ~SSL_OP_NO_SSLv3;
    833                 optionsToClear |= SSL_OP_NO_SSLv3;
    834             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
    835                 optionsToSet &= ~SSL_OP_NO_TLSv1;
    836                 optionsToClear |= SSL_OP_NO_TLSv1;
    837             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
    838                 optionsToSet &= ~SSL_OP_NO_TLSv1_1;
    839                 optionsToClear |= SSL_OP_NO_TLSv1_1;
    840             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
    841                 optionsToSet &= ~SSL_OP_NO_TLSv1_2;
    842                 optionsToClear |= SSL_OP_NO_TLSv1_2;
    843             } else {
    844                 // error checked by checkEnabledProtocols
    845                 throw new IllegalStateException();
    846             }
    847         }
    848 
    849         SSL_set_options(ssl, optionsToSet);
    850         SSL_clear_options(ssl, optionsToClear);
    851     }
    852 
    853     public static String[] checkEnabledProtocols(String[] protocols) {
    854         if (protocols == null) {
    855             throw new IllegalArgumentException("protocols == null");
    856         }
    857         for (int i = 0; i < protocols.length; i++) {
    858             String protocol = protocols[i];
    859             if (protocol == null) {
    860                 throw new IllegalArgumentException("protocols[" + i + "] == null");
    861             }
    862             if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
    863                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))
    864                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1))
    865                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2))) {
    866                 throw new IllegalArgumentException("protocol " + protocol
    867                                                    + " is not supported");
    868             }
    869         }
    870         return protocols;
    871     }
    872 
    873     public static native void SSL_set_cipher_lists(long ssl, String[] ciphers);
    874 
    875     public static void setEnabledCipherSuites(long ssl, String[] cipherSuites) {
    876         checkEnabledCipherSuites(cipherSuites);
    877         List<String> opensslSuites = new ArrayList<String>();
    878         for (int i = 0; i < cipherSuites.length; i++) {
    879             String cipherSuite = cipherSuites[i];
    880             if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
    881                 continue;
    882             }
    883             String openssl = STANDARD_TO_OPENSSL_CIPHER_SUITES.get(cipherSuite);
    884             String cs = (openssl == null) ? cipherSuite : openssl;
    885             opensslSuites.add(cs);
    886         }
    887         SSL_set_cipher_lists(ssl, opensslSuites.toArray(new String[opensslSuites.size()]));
    888     }
    889 
    890     public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
    891         if (cipherSuites == null) {
    892             throw new IllegalArgumentException("cipherSuites == null");
    893         }
    894         // makes sure all suites are valid, throwing on error
    895         for (int i = 0; i < cipherSuites.length; i++) {
    896             String cipherSuite = cipherSuites[i];
    897             if (cipherSuite == null) {
    898                 throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
    899             }
    900             if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
    901                 continue;
    902             }
    903             if (STANDARD_TO_OPENSSL_CIPHER_SUITES.containsKey(cipherSuite)) {
    904                 continue;
    905             }
    906             if (OPENSSL_TO_STANDARD_CIPHER_SUITES.containsKey(cipherSuite)) {
    907                 // TODO log warning about using backward compatability
    908                 continue;
    909             }
    910             throw new IllegalArgumentException("cipherSuite " + cipherSuite + " is not supported.");
    911         }
    912         return cipherSuites;
    913     }
    914 
    915     /*
    916      * See the OpenSSL ssl.h header file for more information.
    917      */
    918     public static final int SSL_VERIFY_NONE =                 0x00;
    919     public static final int SSL_VERIFY_PEER =                 0x01;
    920     public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
    921 
    922     public static native void SSL_set_verify(long sslNativePointer, int mode);
    923 
    924     public static native void SSL_set_session(long sslNativePointer, long sslSessionNativePointer)
    925         throws SSLException;
    926 
    927     public static native void SSL_set_session_creation_enabled(
    928             long sslNativePointer, boolean creationEnabled) throws SSLException;
    929 
    930     public static native void SSL_set_tlsext_host_name(long sslNativePointer, String hostname)
    931             throws SSLException;
    932     public static native String SSL_get_servername(long sslNativePointer);
    933 
    934     /**
    935      * Enables NPN for all SSL connections in the context.
    936      *
    937      * <p>For clients this causes the NPN extension to be included in the
    938      * ClientHello message.
    939      *
    940      * <p>For servers this causes the NPN extension to be included in the
    941      * ServerHello message. The NPN extension will not be included in the
    942      * ServerHello response if the client didn't include it in the ClientHello
    943      * request.
    944      *
    945      * <p>In either case the caller should pass a non-null byte array of NPN
    946      * protocols to {@link #SSL_do_handshake}.
    947      */
    948     public static native void SSL_CTX_enable_npn(long sslCtxNativePointer);
    949 
    950     /**
    951      * Disables NPN for all SSL connections in the context.
    952      */
    953     public static native void SSL_CTX_disable_npn(long sslCtxNativePointer);
    954 
    955     /**
    956      * For clients, sets the list of supported ALPN protocols in wire-format
    957      * (length-prefixed 8-bit strings) on an SSL context.
    958      */
    959     public static native int SSL_CTX_set_alpn_protos(long sslCtxPointer, byte[] protos);
    960 
    961     /**
    962      * Returns the selected ALPN protocol. If the server did not select a
    963      * protocol, {@code null} will be returned.
    964      */
    965     public static native byte[] SSL_get0_alpn_selected(long sslPointer);
    966 
    967     /**
    968      * Returns the sslSessionNativePointer of the negotiated session. If this is
    969      * a server negotiation, supplying the {@code alpnProtocols} will enable
    970      * ALPN negotiation.
    971      */
    972     public static native int SSL_do_handshake(long sslNativePointer,
    973                                               FileDescriptor fd,
    974                                               SSLHandshakeCallbacks shc,
    975                                               int timeoutMillis,
    976                                               boolean client_mode,
    977                                               byte[] npnProtocols,
    978                                               byte[] alpnProtocols)
    979         throws SSLException, SocketTimeoutException, CertificateException;
    980 
    981     public static native byte[] SSL_get_npn_negotiated_protocol(long sslNativePointer);
    982 
    983     /**
    984      * Currently only intended for forcing renegotiation for testing.
    985      * Not used within OpenSSLSocketImpl.
    986      */
    987     public static native void SSL_renegotiate(long sslNativePointer) throws SSLException;
    988 
    989     /**
    990      * Returns the local ASN.1 DER encoded X509 certificates.
    991      */
    992     public static native byte[][] SSL_get_certificate(long sslNativePointer);
    993 
    994     /**
    995      * Returns the peer ASN.1 DER encoded X509 certificates.
    996      */
    997     public static native byte[][] SSL_get_peer_cert_chain(long sslNativePointer);
    998 
    999     /**
   1000      * Reads with the native SSL_read function from the encrypted data stream
   1001      * @return -1 if error or the end of the stream is reached.
   1002      */
   1003     public static native int SSL_read(long sslNativePointer,
   1004                                       FileDescriptor fd,
   1005                                       SSLHandshakeCallbacks shc,
   1006                                       byte[] b, int off, int len, int readTimeoutMillis)
   1007         throws IOException;
   1008 
   1009     /**
   1010      * Writes with the native SSL_write function to the encrypted data stream.
   1011      */
   1012     public static native void SSL_write(long sslNativePointer,
   1013                                         FileDescriptor fd,
   1014                                         SSLHandshakeCallbacks shc,
   1015                                         byte[] b, int off, int len, int writeTimeoutMillis)
   1016         throws IOException;
   1017 
   1018     public static native void SSL_interrupt(long sslNativePointer);
   1019     public static native void SSL_shutdown(long sslNativePointer,
   1020                                            FileDescriptor fd,
   1021                                            SSLHandshakeCallbacks shc) throws IOException;
   1022 
   1023     public static native void SSL_free(long sslNativePointer);
   1024 
   1025     public static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
   1026 
   1027     public static native long SSL_SESSION_get_time(long sslSessionNativePointer);
   1028 
   1029     public static native String SSL_SESSION_get_version(long sslSessionNativePointer);
   1030 
   1031     public static native String SSL_SESSION_cipher(long sslSessionNativePointer);
   1032 
   1033     public static native void SSL_SESSION_free(long sslSessionNativePointer);
   1034 
   1035     public static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
   1036 
   1037     public static native long d2i_SSL_SESSION(byte[] data);
   1038 
   1039     /**
   1040      * A collection of callbacks from the native OpenSSL code that are
   1041      * related to the SSL handshake initiated by SSL_do_handshake.
   1042      */
   1043     public interface SSLHandshakeCallbacks {
   1044         /**
   1045          * Verify that we trust the certificate chain is trusted.
   1046          *
   1047          * @param asn1DerEncodedCertificateChain A chain of ASN.1 DER encoded certificates
   1048          * @param authMethod auth algorithm name
   1049          *
   1050          * @throws CertificateException if the certificate is untrusted
   1051          */
   1052         public void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, String authMethod)
   1053             throws CertificateException;
   1054 
   1055         /**
   1056          * Called on an SSL client when the server requests (or
   1057          * requires a certificate). The client can respond by using
   1058          * SSL_use_certificate and SSL_use_PrivateKey to set a
   1059          * certificate if has an appropriate one available, similar to
   1060          * how the server provides its certificate.
   1061          *
   1062          * @param keyTypes key types supported by the server,
   1063          * convertible to strings with #keyType
   1064          * @param asn1DerEncodedX500Principals CAs known to the server
   1065          */
   1066         public void clientCertificateRequested(byte[] keyTypes,
   1067                                                byte[][] asn1DerEncodedX500Principals)
   1068             throws CertificateEncodingException, SSLException;
   1069 
   1070         /**
   1071          * Called when SSL handshake is completed. Note that this can
   1072          * be after SSL_do_handshake returns when handshake cutthrough
   1073          * is enabled.
   1074          */
   1075         public void handshakeCompleted();
   1076     }
   1077 
   1078     public static native long ERR_peek_last_error();
   1079 }
   1080