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