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