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