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