NativeCrypto.java revision 8acd6134dc84b387608746fbf2054c6d7dcd4f52
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.apache.harmony.xnet.provider.jsse;
18
19import java.io.FileDescriptor;
20import java.io.IOException;
21import java.net.SocketTimeoutException;
22import java.nio.ByteOrder;
23import java.security.MessageDigest;
24import java.security.NoSuchAlgorithmException;
25import java.security.SignatureException;
26import java.security.cert.Certificate;
27import java.security.cert.CertificateEncodingException;
28import java.security.cert.CertificateException;
29import java.security.cert.X509Certificate;
30import java.security.interfaces.ECPrivateKey;
31import java.util.ArrayList;
32import java.util.HashMap;
33import java.util.LinkedHashMap;
34import java.util.List;
35import java.util.Map;
36import javax.crypto.BadPaddingException;
37import javax.crypto.IllegalBlockSizeException;
38import javax.net.ssl.SSLException;
39import javax.security.auth.x500.X500Principal;
40import libcore.io.Memory;
41
42/**
43 * Provides the Java side of our JNI glue for OpenSSL.
44 */
45public final class NativeCrypto {
46
47    // --- OpenSSL library initialization --------------------------------------
48    static {
49        clinit();
50    }
51
52    private native static void clinit();
53
54    // --- ENGINE functions ----------------------------------------------------
55    public static native void ENGINE_load_dynamic();
56
57    public static native long ENGINE_by_id(String id);
58
59    public static native int ENGINE_add(long e);
60
61    public static native int ENGINE_init(long e);
62
63    public static native int ENGINE_finish(long e);
64
65    public static native int ENGINE_free(long e);
66
67    public static native long ENGINE_load_private_key(long e, String key_id);
68
69    public static native String ENGINE_get_id(long engineRef);
70
71    public static native int ENGINE_ctrl_cmd_string(long engineRef, String cmd, String arg,
72            int cmd_optional);
73
74    // --- DSA/RSA public/private key handling functions -----------------------
75
76    public static native long EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
77                                               byte[] pub_key, byte[] priv_key);
78
79    public static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
80            byte[] dmp1, byte[] dmq1, byte[] iqmp);
81
82    public static native long EVP_PKEY_new_mac_key(int type, byte[] key);
83
84    public static native int EVP_PKEY_size(long pkey);
85
86    public static native int EVP_PKEY_type(long pkey);
87
88    public static native String EVP_PKEY_print_public(long pkeyRef);
89
90    public static native String EVP_PKEY_print_private(long pkeyRef);
91
92    public static native void EVP_PKEY_free(long pkey);
93
94    public static native int EVP_PKEY_cmp(long pkey1, long pkey2);
95
96    public static native byte[] i2d_PKCS8_PRIV_KEY_INFO(long pkey);
97
98    public static native long d2i_PKCS8_PRIV_KEY_INFO(byte[] data);
99
100    public static native byte[] i2d_PUBKEY(long pkey);
101
102    public static native long d2i_PUBKEY(byte[] data);
103
104    public static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
105
106    public static native int RSA_size(long pkey);
107
108    public static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, long pkey,
109            int padding);
110
111    public static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, long pkey,
112            int padding) throws BadPaddingException, SignatureException;
113
114    public static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, long pkey,
115            int padding);
116
117    public static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, long pkey,
118            int padding) throws BadPaddingException, SignatureException;
119
120    /**
121     * @return array of {n, e}
122     */
123    public static native byte[][] get_RSA_public_params(long rsa);
124
125    /**
126     * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
127     */
128    public static native byte[][] get_RSA_private_params(long rsa);
129
130    public static native long DSA_generate_key(int primeBits, byte[] seed, byte[] g, byte[] p,
131            byte[] q);
132
133    /**
134     * @return array of {g, p, q, y(pub), x(priv)}
135     */
136    public static native byte[][] get_DSA_params(long dsa);
137
138    public static native byte[] i2d_RSAPublicKey(long rsa);
139
140    public static native byte[] i2d_RSAPrivateKey(long rsa);
141
142    public static native byte[] i2d_DSAPublicKey(long dsa);
143
144    public static native byte[] i2d_DSAPrivateKey(long dsa);
145
146    // --- EC functions --------------------------
147
148    /**
149     * Used to request EC_GROUP_new_curve_GFp to EC_GROUP_new_curve
150     */
151    public static final int EC_CURVE_GFP = 1;
152
153    /**
154     * Used to request EC_GROUP_new_curve_GF2m to EC_GROUP_new_curve
155     */
156    public static final int EC_CURVE_GF2M = 2;
157
158    /**
159     * EC_GROUP_set_asn1_flag: indicates an EC_GROUP is a NamedCurve.
160     */
161    public static final int OPENSSL_EC_NAMED_CURVE = 0x001;
162
163    /**
164     * EC_GROUP_set_point_conversion_form: indicates compressed ASN.1 format
165     */
166    public static final int POINT_CONVERSION_COMPRESSED = 2;
167
168    /**
169     * EC_GROUP_set_point_conversion_form: indicates uncompressed ASN.1 format
170     */
171    public static final int POINT_CONVERSION_UNCOMPRESSED = 4;
172
173    /**
174     * EC_GROUP_set_point_conversion_form: indicates hybrid ASN.1 format
175     */
176    public static final int POINT_CONVERSION_HYBRID = 4;
177
178    public static native long EVP_PKEY_new_EC_KEY(long groupRef, long pubkeyRef, byte[] privkey);
179
180    public static native long EC_GROUP_new_by_curve_name(String curveName);
181
182    public static native long EC_GROUP_new_curve(int type, byte[] p, byte[] a, byte[] b);
183
184    public static native long EC_GROUP_dup(long groupRef);
185
186    public static native void EC_GROUP_set_asn1_flag(long groupRef, int flag);
187
188    public static native void EC_GROUP_set_point_conversion_form(long groupRef, int form);
189
190    public static native String EC_GROUP_get_curve_name(long groupRef);
191
192    public static native byte[][] EC_GROUP_get_curve(long groupRef);
193
194    public static native void EC_GROUP_clear_free(long ctx);
195
196    public static native boolean EC_GROUP_cmp(long ctx1, long ctx2);
197
198    public static native void EC_GROUP_set_generator(long groupCtx, long pointCtx, byte[] n, byte[] h);
199
200    public static native long EC_GROUP_get_generator(long groupCtx);
201
202    public static native int get_EC_GROUP_type(long groupCtx);
203
204    public static native byte[] EC_GROUP_get_order(long groupCtx);
205
206    public static native byte[] EC_GROUP_get_cofactor(long groupCtx);
207
208    public static native long EC_POINT_new(long groupRef);
209
210    public static native void EC_POINT_clear_free(long pointRef);
211
212    public static native boolean EC_POINT_cmp(long groupRef, long pointRef1, long pointRef2);
213
214    public static native byte[][] EC_POINT_get_affine_coordinates(long groupCtx, long pointCtx);
215
216    public static native void EC_POINT_set_affine_coordinates(long groupCtx, long pointCtx, byte[] x,
217            byte[] y);
218
219    public static native long EC_KEY_generate_key(long groupRef);
220
221    public static native long EC_KEY_get0_group(long pkeyRef);
222
223    public static native byte[] EC_KEY_get_private_key(long keyRef);
224
225    public static native long EC_KEY_get_public_key(long keyRef);
226
227    // --- Message digest functions --------------
228
229    public static native long EVP_get_digestbyname(String name);
230
231    public static native int EVP_MD_size(long evp_md);
232
233    public static native int EVP_MD_block_size(long evp_md);
234
235    // --- Message digest context functions --------------
236
237    public static native long EVP_MD_CTX_create();
238
239    public static native void EVP_MD_CTX_init(long ctx);
240
241    public static native void EVP_MD_CTX_destroy(long ctx);
242
243    public static native long EVP_MD_CTX_copy(long ctx);
244
245    // --- Digest handling functions -------------------------------------------
246
247    public static native long EVP_DigestInit(long evp_md);
248
249    public static native void EVP_DigestUpdate(long ctx, byte[] buffer, int offset, int length);
250
251    public static native int EVP_DigestFinal(long ctx, byte[] hash, int offset);
252
253    // --- MAC handling functions ----------------------------------------------
254
255    public static native void EVP_DigestSignInit(long evp_md_ctx, long evp_md, long evp_pkey);
256
257    public static native void EVP_DigestSignUpdate(long evp_md_ctx, byte[] in);
258
259    public static native byte[] EVP_DigestSignFinal(long evp_md_ctx);
260
261    // --- Signature handling functions ----------------------------------------
262
263    public static native long EVP_SignInit(String algorithm);
264
265    public static native void EVP_SignUpdate(long ctx, byte[] buffer,
266                                               int offset, int length);
267
268    public static native int EVP_SignFinal(long ctx, byte[] signature, int offset, long key);
269
270    public static native long EVP_VerifyInit(String algorithm);
271
272    public static native void EVP_VerifyUpdate(long ctx, byte[] buffer,
273                                               int offset, int length);
274
275    public static native int EVP_VerifyFinal(long ctx, byte[] signature,
276                                             int offset, int length, long key);
277
278
279    // --- Block ciphers -------------------------------------------------------
280
281    public static native long EVP_get_cipherbyname(String string);
282
283    public static native void EVP_CipherInit_ex(long ctx, long evpCipher, byte[] key, byte[] iv,
284            boolean encrypting);
285
286    public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
287            int inOffset, int inLength);
288
289    public static native int EVP_CipherFinal_ex(long ctx, byte[] out, int outOffset)
290            throws BadPaddingException, IllegalBlockSizeException;
291
292    public static native int EVP_CIPHER_iv_length(long evpCipher);
293
294    public static native long EVP_CIPHER_CTX_new();
295
296    public static native int EVP_CIPHER_CTX_block_size(long ctx);
297
298    public static native int get_EVP_CIPHER_CTX_buf_len(long ctx);
299
300    public static native void EVP_CIPHER_CTX_set_padding(long ctx, boolean enablePadding);
301
302    public static native void EVP_CIPHER_CTX_set_key_length(long ctx, int keyBitSize);
303
304    public static native void EVP_CIPHER_CTX_cleanup(long ctx);
305
306    // --- RAND seeding --------------------------------------------------------
307
308    public static final int RAND_SEED_LENGTH_IN_BYTES = 1024;
309
310    public static native void RAND_seed(byte[] seed);
311
312    public static native int RAND_load_file(String filename, long max_bytes);
313
314    public static native void RAND_bytes(byte[] output);
315
316    // --- ASN.1 objects -------------------------------------------------------
317
318    public static native int OBJ_txt2nid(String oid);
319
320    public static native String OBJ_txt2nid_longName(String oid);
321
322    public static native String OBJ_txt2nid_oid(String oid);
323
324    // --- X509_NAME -----------------------------------------------------------
325
326    public static int X509_NAME_hash(X500Principal principal) {
327        return X509_NAME_hash(principal, "SHA1");
328    }
329    public static int X509_NAME_hash_old(X500Principal principal) {
330        return X509_NAME_hash(principal, "MD5");
331    }
332    private static int X509_NAME_hash(X500Principal principal, String algorithm) {
333        try {
334            byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
335            return Memory.peekInt(digest, 0, ByteOrder.LITTLE_ENDIAN);
336        } catch (NoSuchAlgorithmException e) {
337            throw new AssertionError(e);
338        }
339    }
340
341    // --- SSL handling --------------------------------------------------------
342
343    private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
344    private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
345    private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
346    private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
347
348    public static final Map<String, String> OPENSSL_TO_STANDARD_CIPHER_SUITES
349            = new HashMap<String, String>();
350    public static final Map<String, String> STANDARD_TO_OPENSSL_CIPHER_SUITES
351            = new LinkedHashMap<String, String>();
352
353    private static void add(String standard, String openssl) {
354        OPENSSL_TO_STANDARD_CIPHER_SUITES.put(openssl, standard);
355        STANDARD_TO_OPENSSL_CIPHER_SUITES.put(standard, openssl);
356    }
357
358    /**
359     * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
360     * indication signaling cipher suite value. It is not a real
361     * cipher suite. It is just an indication in the default and
362     * supported cipher suite lists indicates that the implementation
363     * supports secure renegotiation.
364     *
365     * In the RI, its presence means that the SCSV is sent in the
366     * cipher suite list to indicate secure renegotiation support and
367     * its absense means to send an empty TLS renegotiation info
368     * extension instead.
369     *
370     * However, OpenSSL doesn't provide an API to give this level of
371     * control, instead always sending the SCSV and always including
372     * the empty renegotiation info if TLS is used (as opposed to
373     * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
374     * be passed for compatibility as to provide the hint that we
375     * support secure renegotiation.
376     */
377    public static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV
378            = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
379
380    static {
381        // Note these are added in priority order
382        add("SSL_RSA_WITH_RC4_128_MD5",              "RC4-MD5");
383        add("SSL_RSA_WITH_RC4_128_SHA",              "RC4-SHA");
384        add("TLS_RSA_WITH_AES_128_CBC_SHA",          "AES128-SHA");
385        add("TLS_RSA_WITH_AES_256_CBC_SHA",          "AES256-SHA");
386        add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",       "ECDH-ECDSA-RC4-SHA");
387        add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",   "ECDH-ECDSA-AES128-SHA");
388        add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",   "ECDH-ECDSA-AES256-SHA");
389        add("TLS_ECDH_RSA_WITH_RC4_128_SHA",         "ECDH-RSA-RC4-SHA");
390        add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",     "ECDH-RSA-AES128-SHA");
391        add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",     "ECDH-RSA-AES256-SHA");
392        add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",      "ECDHE-ECDSA-RC4-SHA");
393        add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",  "ECDHE-ECDSA-AES128-SHA");
394        add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",  "ECDHE-ECDSA-AES256-SHA");
395        add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",        "ECDHE-RSA-RC4-SHA");
396        add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",    "ECDHE-RSA-AES128-SHA");
397        add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",    "ECDHE-RSA-AES256-SHA");
398        add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",      "DHE-RSA-AES128-SHA");
399        add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA",      "DHE-RSA-AES256-SHA");
400        add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",      "DHE-DSS-AES128-SHA");
401        add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA",      "DHE-DSS-AES256-SHA");
402        add("SSL_RSA_WITH_3DES_EDE_CBC_SHA",         "DES-CBC3-SHA");
403        add("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",  "ECDH-ECDSA-DES-CBC3-SHA");
404        add("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",    "ECDH-RSA-DES-CBC3-SHA");
405        add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "ECDHE-ECDSA-DES-CBC3-SHA");
406        add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",   "ECDHE-RSA-DES-CBC3-SHA");
407        add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",     "EDH-RSA-DES-CBC3-SHA");
408        add("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",     "EDH-DSS-DES-CBC3-SHA");
409        add("SSL_RSA_WITH_DES_CBC_SHA",              "DES-CBC-SHA");
410        add("SSL_DHE_RSA_WITH_DES_CBC_SHA",          "EDH-RSA-DES-CBC-SHA");
411        add("SSL_DHE_DSS_WITH_DES_CBC_SHA",          "EDH-DSS-DES-CBC-SHA");
412        add("SSL_RSA_EXPORT_WITH_RC4_40_MD5",        "EXP-RC4-MD5");
413        add("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",     "EXP-DES-CBC-SHA");
414        add("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-RSA-DES-CBC-SHA");
415        add("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-DSS-DES-CBC-SHA");
416        add("SSL_RSA_WITH_NULL_MD5",                 "NULL-MD5");
417        add("SSL_RSA_WITH_NULL_SHA",                 "NULL-SHA");
418        add("TLS_ECDH_ECDSA_WITH_NULL_SHA",          "ECDH-ECDSA-NULL-SHA");
419        add("TLS_ECDH_RSA_WITH_NULL_SHA",            "ECDH-RSA-NULL-SHA");
420        add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",         "ECDHE-ECDSA-NULL-SHA");
421        add("TLS_ECDHE_RSA_WITH_NULL_SHA",           "ECDHE-RSA-NULL-SHA");
422        add("SSL_DH_anon_WITH_RC4_128_MD5",          "ADH-RC4-MD5");
423        add("TLS_DH_anon_WITH_AES_128_CBC_SHA",      "ADH-AES128-SHA");
424        add("TLS_DH_anon_WITH_AES_256_CBC_SHA",      "ADH-AES256-SHA");
425        add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",     "ADH-DES-CBC3-SHA");
426        add("SSL_DH_anon_WITH_DES_CBC_SHA",          "ADH-DES-CBC-SHA");
427        add("TLS_ECDH_anon_WITH_RC4_128_SHA",        "AECDH-RC4-SHA");
428        add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",    "AECDH-AES128-SHA");
429        add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",    "AECDH-AES256-SHA");
430        add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",   "AECDH-DES-CBC3-SHA");
431        add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",    "EXP-ADH-RC4-MD5");
432        add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", "EXP-ADH-DES-CBC-SHA");
433        add("TLS_ECDH_anon_WITH_NULL_SHA",           "AECDH-NULL-SHA");
434
435        // No Kerberos in Android
436        // add("TLS_KRB5_WITH_RC4_128_SHA",           "KRB5-RC4-SHA");
437        // add("TLS_KRB5_WITH_RC4_128_MD5",           "KRB5-RC4-MD5");
438        // add("TLS_KRB5_WITH_3DES_EDE_CBC_SHA",      "KRB5-DES-CBC3-SHA");
439        // add("TLS_KRB5_WITH_3DES_EDE_CBC_MD5",      "KRB5-DES-CBC3-MD5");
440        // add("TLS_KRB5_WITH_DES_CBC_SHA",           "KRB5-DES-CBC-SHA");
441        // add("TLS_KRB5_WITH_DES_CBC_MD5",           "KRB5-DES-CBC-MD5");
442        // add("TLS_KRB5_EXPORT_WITH_RC4_40_SHA",     "EXP-KRB5-RC4-SHA");
443        // add("TLS_KRB5_EXPORT_WITH_RC4_40_MD5",     "EXP-KRB5-RC4-MD5");
444        // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", "EXP-KRB5-DES-CBC-SHA");
445        // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", "EXP-KRB5-DES-CBC-MD5");
446
447        // not implemented by either RI or OpenSSL
448        // add("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", null);
449        // add("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", null);
450
451        // EXPORT1024 suites were never standardized but were widely implemented.
452        // OpenSSL 0.9.8c and later have disabled TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES
453        // add("SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA", "EXP1024-DES-CBC-SHA");
454        // add("SSL_RSA_EXPORT1024_WITH_RC4_56_SHA",  "EXP1024-RC4-SHA");
455
456        // No RC2
457        // add("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5",  "EXP-RC2-CBC-MD5");
458        // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", "EXP-KRB5-RC2-CBC-SHA");
459        // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", "EXP-KRB5-RC2-CBC-MD5");
460
461        // PSK is Private Shared Key - didn't exist in Froyo's openssl - no JSSE equivalent
462        // add(null, "PSK-3DES-EDE-CBC-SHA");
463        // add(null, "PSK-AES128-CBC-SHA");
464        // add(null, "PSK-AES256-CBC-SHA");
465        // add(null, "PSK-RC4-SHA");
466
467        // Signaling Cipher Suite Value for secure renegotiation handled as special case.
468        // add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", null);
469    }
470
471    private static final String[] SUPPORTED_CIPHER_SUITES;
472    static {
473        int size = STANDARD_TO_OPENSSL_CIPHER_SUITES.size();
474        SUPPORTED_CIPHER_SUITES = new String[size + 1];
475        STANDARD_TO_OPENSSL_CIPHER_SUITES.keySet().toArray(SUPPORTED_CIPHER_SUITES);
476        SUPPORTED_CIPHER_SUITES[size] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
477    }
478
479    // EVP_PKEY types from evp.h and objects.h
480    public static final int EVP_PKEY_RSA  = 6;   // NID_rsaEcnryption
481    public static final int EVP_PKEY_DSA  = 116; // NID_dsa
482    public static final int EVP_PKEY_DH   = 28;  // NID_dhKeyAgreement
483    public static final int EVP_PKEY_EC   = 408; // NID_X9_62_id_ecPublicKey
484    public static final int EVP_PKEY_HMAC = 855; // NID_hmac
485    public static final int EVP_PKEY_CMAC = 894; // NID_cmac
486
487    // RSA padding modes from rsa.h
488    public static final int RSA_PKCS1_PADDING = 1;
489    public static final int RSA_NO_PADDING    = 3;
490
491    // SSL mode from ssl.h
492    public static final long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000020L;
493
494    // SSL options from ssl.h
495    public static final long SSL_OP_NO_TICKET                              = 0x00004000L;
496    public static final long SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 0x00010000L;
497    public static final long SSL_OP_NO_SSLv3                               = 0x02000000L;
498    public static final long SSL_OP_NO_TLSv1                               = 0x04000000L;
499    public static final long SSL_OP_NO_TLSv1_1                             = 0x10000000L;
500    public static final long SSL_OP_NO_TLSv1_2                             = 0x08000000L;
501
502    public static native long SSL_CTX_new();
503
504    public static String[] getDefaultCipherSuites() {
505        return new String[] {
506            "SSL_RSA_WITH_RC4_128_MD5",
507            "SSL_RSA_WITH_RC4_128_SHA",
508            "TLS_RSA_WITH_AES_128_CBC_SHA",
509            "TLS_RSA_WITH_AES_256_CBC_SHA",
510            "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
511            "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
512            "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
513            "TLS_ECDH_RSA_WITH_RC4_128_SHA",
514            "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
515            "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
516            "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
517            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
518            "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
519            "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
520            "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
521            "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
522            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
523            "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
524            "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
525            "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
526            "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
527            "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
528            "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
529            "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
530            "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
531            "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
532            "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
533            "SSL_RSA_WITH_DES_CBC_SHA",
534            "SSL_DHE_RSA_WITH_DES_CBC_SHA",
535            "SSL_DHE_DSS_WITH_DES_CBC_SHA",
536            "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
537            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
538            "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
539            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
540            TLS_EMPTY_RENEGOTIATION_INFO_SCSV
541        };
542    }
543
544    public static String[] getSupportedCipherSuites() {
545        return SUPPORTED_CIPHER_SUITES.clone();
546    }
547
548    public static native void SSL_CTX_free(long ssl_ctx);
549
550    public static native void SSL_CTX_set_session_id_context(long ssl_ctx, byte[] sid_ctx);
551
552    public static native long SSL_new(long ssl_ctx) throws SSLException;
553
554    public static native void SSL_enable_tls_channel_id(long ssl) throws SSLException;
555
556    public static native byte[] SSL_get_tls_channel_id(long ssl) throws SSLException;
557
558    public static native void SSL_use_OpenSSL_PrivateKey_for_tls_channel_id(long ssl, long pkey)
559            throws SSLException;
560
561    public static native void SSL_use_PKCS8_PrivateKey_for_tls_channel_id(
562            long ssl, byte[] pkcs8EncodedPrivateKey) throws SSLException;
563
564    public static void SSL_set1_tls_channel_id(long ssl, ECPrivateKey privateKey)
565            throws SSLException {
566        if (privateKey == null) {
567            throw new NullPointerException("privateKey == null");
568        } else if (privateKey instanceof OpenSSLECPrivateKey) {
569            OpenSSLKey openSslPrivateKey = ((OpenSSLECPrivateKey) privateKey).getOpenSSLKey();
570            SSL_use_OpenSSL_PrivateKey_for_tls_channel_id(ssl, openSslPrivateKey.getPkeyContext());
571        } else if ("PKCS#8".equals(privateKey.getFormat())) {
572            byte[] pkcs8EncodedKey = privateKey.getEncoded();
573            SSL_use_PKCS8_PrivateKey_for_tls_channel_id(ssl, pkcs8EncodedKey);
574        } else {
575            throw new SSLException("Unsupported Channel ID private key type:" +
576                    " class: " + privateKey.getClass() + ", format: " + privateKey.getFormat());
577        }
578    }
579
580    public static byte[][] encodeCertificates(Certificate[] certificates)
581            throws CertificateEncodingException {
582        byte[][] certificateBytes = new byte[certificates.length][];
583        for (int i = 0; i < certificates.length; i++) {
584            certificateBytes[i] = certificates[i].getEncoded();
585        }
586        return certificateBytes;
587    }
588
589    public static native void SSL_use_certificate(long ssl, byte[][] asn1DerEncodedCertificateChain);
590
591    public static native void SSL_use_OpenSSL_PrivateKey(long ssl, long pkey);
592
593    public static native void SSL_use_PrivateKey(long ssl, byte[] pkcs8EncodedPrivateKey);
594
595    public static native void SSL_check_private_key(long ssl) throws SSLException;
596
597    public static byte[][] encodeIssuerX509Principals(X509Certificate[] certificates)
598            throws CertificateEncodingException {
599        byte[][] principalBytes = new byte[certificates.length][];
600        for (int i = 0; i < certificates.length; i++) {
601            principalBytes[i] = certificates[i].getIssuerX500Principal().getEncoded();
602        }
603        return principalBytes;
604    }
605
606    public static native void SSL_set_client_CA_list(long ssl, byte[][] asn1DerEncodedX500Principals);
607
608    public static native long SSL_get_mode(long ssl);
609
610    public static native long SSL_set_mode(long ssl, long mode);
611
612    public static native long SSL_clear_mode(long ssl, long mode);
613
614    public static native long SSL_get_options(long ssl);
615
616    public static native long SSL_set_options(long ssl, long options);
617
618    public static native long SSL_clear_options(long ssl, long options);
619
620    public static String[] getDefaultProtocols() {
621        return new String[] { SUPPORTED_PROTOCOL_SSLV3,
622                              SUPPORTED_PROTOCOL_TLSV1,
623        };
624    }
625
626    public static String[] getSupportedProtocols() {
627        return new String[] { SUPPORTED_PROTOCOL_SSLV3,
628                              SUPPORTED_PROTOCOL_TLSV1,
629                              SUPPORTED_PROTOCOL_TLSV1_1,
630                              SUPPORTED_PROTOCOL_TLSV1_2,
631        };
632    }
633
634    public static void setEnabledProtocols(long ssl, String[] protocols) {
635        checkEnabledProtocols(protocols);
636        // openssl uses negative logic letting you disable protocols.
637        // so first, assume we need to set all (disable all) and clear none (enable none).
638        // in the loop, selectively move bits from set to clear (from disable to enable)
639        long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
640        long optionsToClear = 0;
641        for (int i = 0; i < protocols.length; i++) {
642            String protocol = protocols[i];
643            if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
644                optionsToSet &= ~SSL_OP_NO_SSLv3;
645                optionsToClear |= SSL_OP_NO_SSLv3;
646            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
647                optionsToSet &= ~SSL_OP_NO_TLSv1;
648                optionsToClear |= SSL_OP_NO_TLSv1;
649            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
650                optionsToSet &= ~SSL_OP_NO_TLSv1_1;
651                optionsToClear |= SSL_OP_NO_TLSv1_1;
652            } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
653                optionsToSet &= ~SSL_OP_NO_TLSv1_2;
654                optionsToClear |= SSL_OP_NO_TLSv1_2;
655            } else {
656                // error checked by checkEnabledProtocols
657                throw new IllegalStateException();
658            }
659        }
660
661        SSL_set_options(ssl, optionsToSet);
662        SSL_clear_options(ssl, optionsToClear);
663    }
664
665    public static String[] checkEnabledProtocols(String[] protocols) {
666        if (protocols == null) {
667            throw new IllegalArgumentException("protocols == null");
668        }
669        for (int i = 0; i < protocols.length; i++) {
670            String protocol = protocols[i];
671            if (protocol == null) {
672                throw new IllegalArgumentException("protocols[" + i + "] == null");
673            }
674            if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
675                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))
676                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1))
677                    && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2))) {
678                throw new IllegalArgumentException("protocol " + protocol
679                                                   + " is not supported");
680            }
681        }
682        return protocols;
683    }
684
685    public static native void SSL_set_cipher_lists(long ssl, String[] ciphers);
686
687    public static void setEnabledCipherSuites(long ssl, String[] cipherSuites) {
688        checkEnabledCipherSuites(cipherSuites);
689        List<String> opensslSuites = new ArrayList<String>();
690        for (int i = 0; i < cipherSuites.length; i++) {
691            String cipherSuite = cipherSuites[i];
692            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
693                continue;
694            }
695            String openssl = STANDARD_TO_OPENSSL_CIPHER_SUITES.get(cipherSuite);
696            String cs = (openssl == null) ? cipherSuite : openssl;
697            opensslSuites.add(cs);
698        }
699        SSL_set_cipher_lists(ssl, opensslSuites.toArray(new String[opensslSuites.size()]));
700    }
701
702    public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
703        if (cipherSuites == null) {
704            throw new IllegalArgumentException("cipherSuites == null");
705        }
706        // makes sure all suites are valid, throwing on error
707        for (int i = 0; i < cipherSuites.length; i++) {
708            String cipherSuite = cipherSuites[i];
709            if (cipherSuite == null) {
710                throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
711            }
712            if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
713                continue;
714            }
715            if (STANDARD_TO_OPENSSL_CIPHER_SUITES.containsKey(cipherSuite)) {
716                continue;
717            }
718            if (OPENSSL_TO_STANDARD_CIPHER_SUITES.containsKey(cipherSuite)) {
719                // TODO log warning about using backward compatability
720                continue;
721            }
722            throw new IllegalArgumentException("cipherSuite " + cipherSuite + " is not supported.");
723        }
724        return cipherSuites;
725    }
726
727    /*
728     * See the OpenSSL ssl.h header file for more information.
729     */
730    public static final int SSL_VERIFY_NONE =                 0x00;
731    public static final int SSL_VERIFY_PEER =                 0x01;
732    public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
733
734    public static native void SSL_set_verify(long sslNativePointer, int mode);
735
736    public static native void SSL_set_session(long sslNativePointer, long sslSessionNativePointer)
737        throws SSLException;
738
739    public static native void SSL_set_session_creation_enabled(
740            long sslNativePointer, boolean creationEnabled) throws SSLException;
741
742    public static native void SSL_set_tlsext_host_name(long sslNativePointer, String hostname)
743            throws SSLException;
744    public static native String SSL_get_servername(long sslNativePointer);
745
746    /**
747     * Enables NPN for all SSL connections in the context.
748     *
749     * <p>For clients this causes the NPN extension to be included in the
750     * ClientHello message.
751     *
752     * <p>For servers this causes the NPN extension to be included in the
753     * ServerHello message. The NPN extension will not be included in the
754     * ServerHello response if the client didn't include it in the ClientHello
755     * request.
756     *
757     * <p>In either case the caller should pass a non-null byte array of NPN
758     * protocols to {@link #SSL_do_handshake}.
759     */
760    public static native void SSL_CTX_enable_npn(long sslCtxNativePointer);
761
762    /**
763     * Disables NPN for all SSL connections in the context.
764     */
765    public static native void SSL_CTX_disable_npn(long sslCtxNativePointer);
766
767    /**
768     * Returns the sslSessionNativePointer of the negotiated session
769     */
770    public static native int SSL_do_handshake(long sslNativePointer,
771                                              FileDescriptor fd,
772                                              SSLHandshakeCallbacks shc,
773                                              int timeoutMillis,
774                                              boolean client_mode,
775                                              byte[] npnProtocols)
776        throws SSLException, SocketTimeoutException, CertificateException;
777
778    public static native byte[] SSL_get_npn_negotiated_protocol(long sslNativePointer);
779
780    /**
781     * Currently only intended for forcing renegotiation for testing.
782     * Not used within OpenSSLSocketImpl.
783     */
784    public static native void SSL_renegotiate(long sslNativePointer) throws SSLException;
785
786    /**
787     * Returns the local ASN.1 DER encoded X509 certificates.
788     */
789    public static native byte[][] SSL_get_certificate(long sslNativePointer);
790
791    /**
792     * Returns the peer ASN.1 DER encoded X509 certificates.
793     */
794    public static native byte[][] SSL_get_peer_cert_chain(long sslNativePointer);
795
796    /**
797     * Reads with the native SSL_read function from the encrypted data stream
798     * @return -1 if error or the end of the stream is reached.
799     */
800    public static native int SSL_read(long sslNativePointer,
801                                      FileDescriptor fd,
802                                      SSLHandshakeCallbacks shc,
803                                      byte[] b, int off, int len, int readTimeoutMillis)
804        throws IOException;
805
806    /**
807     * Writes with the native SSL_write function to the encrypted data stream.
808     */
809    public static native void SSL_write(long sslNativePointer,
810                                        FileDescriptor fd,
811                                        SSLHandshakeCallbacks shc,
812                                        byte[] b, int off, int len, int writeTimeoutMillis)
813        throws IOException;
814
815    public static native void SSL_interrupt(long sslNativePointer);
816    public static native void SSL_shutdown(long sslNativePointer,
817                                           FileDescriptor fd,
818                                           SSLHandshakeCallbacks shc) throws IOException;
819
820    public static native void SSL_free(long sslNativePointer);
821
822    public static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
823
824    public static native long SSL_SESSION_get_time(long sslSessionNativePointer);
825
826    public static native String SSL_SESSION_get_version(long sslSessionNativePointer);
827
828    public static native String SSL_SESSION_cipher(long sslSessionNativePointer);
829
830    public static native void SSL_SESSION_free(long sslSessionNativePointer);
831
832    public static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
833
834    public static native long d2i_SSL_SESSION(byte[] data);
835
836    /**
837     * A collection of callbacks from the native OpenSSL code that are
838     * related to the SSL handshake initiated by SSL_do_handshake.
839     */
840    public interface SSLHandshakeCallbacks {
841        /**
842         * Verify that we trust the certificate chain is trusted.
843         *
844         * @param asn1DerEncodedCertificateChain A chain of ASN.1 DER encoded certificates
845         * @param authMethod auth algorithm name
846         *
847         * @throws CertificateException if the certificate is untrusted
848         */
849        public void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, String authMethod)
850            throws CertificateException;
851
852        /**
853         * Called on an SSL client when the server requests (or
854         * requires a certificate). The client can respond by using
855         * SSL_use_certificate and SSL_use_PrivateKey to set a
856         * certificate if has an appropriate one available, similar to
857         * how the server provides its certificate.
858         *
859         * @param keyTypes key types supported by the server,
860         * convertible to strings with #keyType
861         * @param asn1DerEncodedX500Principals CAs known to the server
862         */
863        public void clientCertificateRequested(byte[] keyTypes,
864                                               byte[][] asn1DerEncodedX500Principals)
865            throws CertificateEncodingException, SSLException;
866
867        /**
868         * Called when SSL handshake is completed. Note that this can
869         * be after SSL_do_handshake returns when handshake cutthrough
870         * is enabled.
871         */
872        public void handshakeCompleted();
873    }
874
875    public static native long ERR_peek_last_error();
876}
877