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