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