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