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