View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  /*
17   *  Licensed to the Apache Software Foundation (ASF) under one or more
18   *  contributor license agreements.  See the NOTICE file distributed with
19   *  this work for additional information regarding copyright ownership.
20   *  The ASF licenses this file to You under the Apache License, Version 2.0
21   *  (the "License"); you may not use this file except in compliance with
22   *  the License.  You may obtain a copy of the License at
23   *
24   *      http://www.apache.org/licenses/LICENSE-2.0
25   *
26   *  Unless required by applicable law or agreed to in writing, software
27   *  distributed under the License is distributed on an "AS IS" BASIS,
28   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29   *  See the License for the specific language governing permissions and
30   *  limitations under the License.
31   */
32  package io.netty.internal.tcnative;
33  
34  import java.nio.ByteBuffer;
35  
36  import javax.net.ssl.SSLEngine;
37  
38  import static io.netty.internal.tcnative.NativeStaticallyReferencedJniMethods.*;
39  
40  public final class SSL {
41  
42      private SSL() { }
43  
44      /*
45       * Define the SSL Protocol options
46       */
47      public static final int SSL_PROTOCOL_NONE  = 0;
48      public static final int SSL_PROTOCOL_SSLV2 = (1<<0);
49      public static final int SSL_PROTOCOL_SSLV3 = (1<<1);
50      public static final int SSL_PROTOCOL_TLSV1 = (1<<2);
51      public static final int SSL_PROTOCOL_TLSV1_1 = (1<<3);
52      public static final int SSL_PROTOCOL_TLSV1_2 = (1<<4);
53  
54      /** TLS_*method according to <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_new.html">SSL_CTX_new</a> */
55      public static final int SSL_PROTOCOL_TLS   = (SSL_PROTOCOL_SSLV3 | SSL_PROTOCOL_TLSV1 | SSL_PROTOCOL_TLSV1_1 | SSL_PROTOCOL_TLSV1_2);
56      public static final int SSL_PROTOCOL_ALL   = (SSL_PROTOCOL_SSLV2 | SSL_PROTOCOL_TLS);
57  
58      /*
59       * Define the SSL verify levels
60       */
61      public static final int SSL_CVERIFY_IGNORED            = -1;
62      public static final int SSL_CVERIFY_NONE               = 0;
63      public static final int SSL_CVERIFY_OPTIONAL           = 1;
64      public static final int SSL_CVERIFY_REQUIRED           = 2;
65  
66      public static final int SSL_OP_CIPHER_SERVER_PREFERENCE = sslOpCipherServerPreference();
67      public static final int SSL_OP_NO_SSLv2 = sslOpNoSSLv2();
68      public static final int SSL_OP_NO_SSLv3 = sslOpNoSSLv3();
69      public static final int SSL_OP_NO_TLSv1 = sslOpNoTLSv1();
70      public static final int SSL_OP_NO_TLSv1_1 = sslOpNoTLSv11();
71      public static final int SSL_OP_NO_TLSv1_2 = sslOpNoTLSv12();
72      public static final int SSL_OP_NO_TICKET = sslOpNoTicket();
73  
74      public static final int SSL_OP_NO_COMPRESSION = sslOpNoCompression();
75  
76      public static final int SSL_MODE_CLIENT         = 0;
77      public static final int SSL_MODE_SERVER         = 1;
78      public static final int SSL_MODE_COMBINED       = 2;
79  
80      public static final long SSL_SESS_CACHE_OFF = sslSessCacheOff();
81      public static final long SSL_SESS_CACHE_SERVER = sslSessCacheServer();
82  
83      public static final int SSL_SELECTOR_FAILURE_NO_ADVERTISE = 0;
84      public static final int SSL_SELECTOR_FAILURE_CHOOSE_MY_LAST_PROTOCOL = 1;
85  
86      public static final int SSL_ST_CONNECT = sslStConnect();
87      public static final int SSL_ST_ACCEPT =  sslStAccept();
88  
89      public static final int SSL_MODE_ENABLE_PARTIAL_WRITE           = sslModeEnablePartialWrite();
90      public static final int SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER     = sslModeAcceptMovingWriteBuffer();
91      public static final int SSL_MODE_RELEASE_BUFFERS                = sslModeReleaseBuffers();
92  
93      public static final int SSL_MAX_PLAINTEXT_LENGTH = sslMaxPlaintextLength();
94      /**
95       * The <a href="https://tools.ietf.org/html/rfc5246#section-6.2.1">TLS 1.2 RFC</a> defines the maximum length to be
96       * {@link #SSL_MAX_PLAINTEXT_LENGTH}, but there are some implementations such as
97       * <a href="http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/d5a00b1e8f78/src/share/classes/sun/security/ssl/SSLSessionImpl.java#l793">OpenJDK's SSLEngineImpl</a>
98       * that also allow sending larger packets. This can be used as a upper bound for data to support legacy systems.
99       */
100     public static final int SSL_MAX_RECORD_LENGTH = sslMaxRecordLength();
101 
102     // https://www.openssl.org/docs/man1.0.2/crypto/X509_check_host.html
103     public static final int X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = x509CheckFlagAlwaysCheckSubject();
104     public static final int X509_CHECK_FLAG_NO_WILD_CARDS = x509CheckFlagDisableWildCards();
105     public static final int X509_CHECK_FLAG_NO_PARTIAL_WILD_CARDS = x509CheckFlagNoPartialWildCards();
106     public static final int X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = x509CheckFlagMultiLabelWildCards();
107 
108     /* Return OpenSSL version number */
109     public static native int version();
110 
111     /* Return OpenSSL version string */
112     public static native String versionString();
113 
114     /**
115      * Initialize OpenSSL support.
116      *
117      * This function needs to be called once for the
118      * lifetime of JVM. See {@link Library#initialize(String, String)}
119      *
120      * @param engine Support for external a Crypto Device ("engine"),
121      *                usually a hardware accelerator card for crypto operations.
122      * @return APR status code
123      */
124     static native int initialize(String engine);
125 
126     /**
127      * Initialize new in-memory BIO that is located in the secure heap.
128      *
129      * @return New BIO handle
130      * @throws Exception if an error happened.
131      */
132     public static native long newMemBIO() throws Exception;
133 
134     /**
135      * Return last SSL error string
136      *
137      * @return the last SSL error string.
138      */
139     public static native String getLastError();
140 
141     /*
142      * Begin Twitter API additions
143      */
144 
145     public static final int SSL_SENT_SHUTDOWN = sslSendShutdown();
146     public static final int SSL_RECEIVED_SHUTDOWN = sslReceivedShutdown();
147 
148     public static final int SSL_ERROR_NONE             = sslErrorNone();
149     public static final int SSL_ERROR_SSL              = sslErrorSSL();
150     public static final int SSL_ERROR_WANT_READ        = sslErrorWantRead();
151     public static final int SSL_ERROR_WANT_WRITE       = sslErrorWantWrite();
152     public static final int SSL_ERROR_WANT_X509_LOOKUP = sslErrorWantX509Lookup();
153     public static final int SSL_ERROR_SYSCALL          = sslErrorSyscall(); /* look at error stack/return value/errno */
154     public static final int SSL_ERROR_ZERO_RETURN      = sslErrorZeroReturn();
155     public static final int SSL_ERROR_WANT_CONNECT     = sslErrorWantConnect();
156     public static final int SSL_ERROR_WANT_ACCEPT      = sslErrorWantAccept();
157 
158     /**
159      * SSL_new
160      * @param ctx Server or Client context to use.
161      * @param server if true configure SSL instance to use accept handshake routines
162      *               if false configure SSL instance to use connect handshake routines
163      * @return pointer to SSL instance (SSL *)
164      */
165     public static native long newSSL(long ctx, boolean server);
166 
167     /**
168      * SSL_get_error
169      * @param ssl SSL pointer (SSL *)
170      * @param ret TLS/SSL I/O return value
171      * @return the error code
172      */
173     public static native int getError(long ssl, int ret);
174 
175     /**
176      * BIO_write
177      * @param bioAddress The address of a {@code BIO*}.
178      * @param wbufAddress The address of a native {@code char*}.
179      * @param wlen The length to write starting at {@code wbufAddress}.
180      * @return The number of bytes that were written.
181      * See <a href="https://www.openssl.org/docs/man1.0.1/crypto/BIO_write.html">BIO_write</a> for exceptional return values.
182      */
183     public static native int bioWrite(long bioAddress, long wbufAddress, int wlen);
184 
185     /**
186      * Initialize the BIO for the SSL instance. This is a custom BIO which is designed to play nicely with a direct
187      * {@link ByteBuffer}. Because it is a special BIO it requires special usage such that
188      * {@link #bioSetByteBuffer(long, long, int, boolean)} and {@link #bioClearByteBuffer(long)} are called in order to provide
189      * to supply data to SSL, and also to ensure the internal SSL buffering mechanism is expecting write at the appropriate times.
190      *
191      * @param ssl the SSL instance (SSL *)
192      * @param nonApplicationBufferSize The size of the internal buffer for write operations that are not
193      *                                 initiated directly by the application attempting to encrypt data.
194      *                                 Must be &gt;{@code 0}.
195      * @return pointer to the Network BIO (BIO *).
196      *         The memory is owned by {@code ssl} and will be cleaned up by {@link #freeSSL(long)}.
197      */
198     public static native long bioNewByteBuffer(long ssl, int nonApplicationBufferSize);
199 
200     /**
201      * Set the memory location which that OpenSSL's internal BIO will use to write encrypted data to, or read encrypted
202      * data from.
203      * <p>
204      * After you are done buffering data you should call {@link #bioClearByteBuffer(long)}.
205      * @param bio {@code BIO*}.
206      * @param bufferAddress The memory address (typically from a direct {@link ByteBuffer}) which will be used
207      *                    to either write encrypted data to, or read encrypted data from by OpenSSL's internal BIO pair.
208      * @param maxUsableBytes The maximum usable length in bytes starting at {@code bufferAddress}.
209      * @param isSSLWriteSink {@code true} if this buffer is expected to buffer data as a result of calls to {@code SSL_write}.
210      *                       {@code false} if this buffer is expected to buffer data as a result of calls to {@code SSL_read}.
211      */
212     public static native void bioSetByteBuffer(long bio, long bufferAddress, int maxUsableBytes, boolean isSSLWriteSink);
213 
214     /**
215      * After you are done buffering data from {@link #bioSetByteBuffer(long, long, int, boolean)}, this will ensure the
216      * internal SSL write buffers are ready to capture data which may unexpectedly happen (e.g. handshake, renegotiation, etc..).
217      * @param bio {@code BIO*}.
218      */
219     public static native void bioClearByteBuffer(long bio);
220 
221     /**
222      * Flush any pending bytes in the internal SSL write buffer.
223      * <p>
224      * This does the same thing as {@code BIO_flush} for a {@code BIO*} of type {@link #bioNewByteBuffer(long, int)} but
225      * returns the number of bytes that were flushed.
226      * @param bio {@code BIO*}.
227      * @return The number of bytes that were flushed.
228      */
229     public static native int bioFlushByteBuffer(long bio);
230 
231     /**
232      * Get the remaining length of the {@link ByteBuffer} set by {@link #bioSetByteBuffer(long, long, int, boolean)}.
233      * @param bio {@code BIO*}.
234      * @return The remaining length of the {@link ByteBuffer} set by {@link #bioSetByteBuffer(long, long, int, boolean)}.
235      */
236     public static native int bioLengthByteBuffer(long bio);
237 
238     /**
239      * Get the amount of data pending in buffer used for non-application writes.
240      * This value will not exceed the value configured in {@link #bioNewByteBuffer(long, int)}.
241      * @param bio {@code BIO*}.
242      * @return the amount of data pending in buffer used for non-application writes.
243      */
244     public static native int bioLengthNonApplication(long bio);
245 
246     /**
247      * The number of bytes pending in SSL which can be read immediately.
248      * See <a href="https://www.openssl.org/docs/man1.0.1/ssl/SSL_pending.html">SSL_pending</a>.
249      * @param ssl the SSL instance (SSL *)
250      * @return The number of bytes pending in SSL which can be read immediately.
251      */
252     public static native int sslPending(long ssl);
253 
254     /**
255      * SSL_write
256      * @param ssl the SSL instance (SSL *)
257      * @param wbuf the memory address of the buffer
258      * @param wlen the length
259      * @return the number of written bytes
260      */
261     public static native int writeToSSL(long ssl, long wbuf, int wlen);
262 
263     /**
264      * SSL_read
265      * @param ssl the SSL instance (SSL *)
266      * @param rbuf the memory address of the buffer
267      * @param rlen the length
268      * @return the number of read bytes
269      */
270     public static native int readFromSSL(long ssl, long rbuf, int rlen);
271 
272     /**
273      * SSL_get_shutdown
274      * @param ssl the SSL instance (SSL *)
275      * @return the return code of {@code SSL_get_shutdown}
276      */
277     public static native int getShutdown(long ssl);
278 
279     /**
280      * SSL_set_shutdown
281      * @param ssl the SSL instance (SSL *)
282      * @param mode the mode to use
283      */
284     public static native void setShutdown(long ssl, int mode);
285 
286     /**
287      * SSL_free
288      * @param ssl the SSL instance (SSL *)
289      */
290     public static native void freeSSL(long ssl);
291 
292     /**
293      * BIO_free
294      * @param bio the BIO
295      */
296     public static native void freeBIO(long bio);
297 
298     /**
299      * SSL_shutdown
300      * @param ssl the SSL instance (SSL *)
301      * @return the return code of {@code SSL_shutdown}
302      */
303     public static native int shutdownSSL(long ssl);
304 
305     /**
306      * Get the error number representing the last error OpenSSL encountered on this thread.
307      * @return the last error code for the calling thread.
308      */
309     public static native int getLastErrorNumber();
310 
311     /**
312      * SSL_get_cipher
313      * @param ssl the SSL instance (SSL *)
314      * @return the name of the current cipher.
315      */
316     public static native String getCipherForSSL(long ssl);
317 
318     /**
319      * SSL_get_version
320      * @param ssl the SSL instance (SSL *)
321      * @return the version.
322      */
323     public static native String getVersion(long ssl);
324 
325     /**
326      * SSL_do_handshake
327      * @param ssl the SSL instance (SSL *)
328      * @return the return code of {@code SSL_do_handshake}.
329      */
330     public static native int doHandshake(long ssl);
331 
332     /**
333      * SSL_in_init
334      * @param ssl the SSL instance (SSL *)
335      * @return the return code of {@code SSL_in_init}.
336      */
337     public static native int isInInit(long ssl);
338 
339     /**
340      * SSL_get0_next_proto_negotiated
341      * @param ssl the SSL instance (SSL *)
342      * @return the name of the negotiated proto
343      */
344     public static native String getNextProtoNegotiated(long ssl);
345 
346     /*
347      * End Twitter API Additions
348      */
349 
350     /**
351      * SSL_get0_alpn_selected
352      * @param ssl the SSL instance (SSL *)
353      * @return the name of the selected ALPN protocol
354      */
355     public static native String getAlpnSelected(long ssl);
356 
357     /**
358      * Get the peer certificate chain or {@code null} if none was send.
359      * @param ssl the SSL instance (SSL *)
360      * @return the chain or {@code null} if none was send
361      */
362     public static native byte[][] getPeerCertChain(long ssl);
363 
364     /**
365      * Get the peer certificate or {@code null} if non was send.
366      * @param ssl the SSL instance (SSL *)
367      * @return the peer certificate or {@code null} if none was send
368      */
369     public static native byte[] getPeerCertificate(long ssl);
370 
371     /**
372      * Get the error string representing for the given {@code errorNumber}.
373      *
374      * @param errorNumber the error number / code
375      * @return the error string
376      */
377     public static native String getErrorString(long errorNumber);
378 
379     /**
380      * SSL_get_time
381      * @param ssl the SSL instance (SSL *)
382      * @return returns the time at which the session ssl was established. The time is given in seconds since the Epoch
383      */
384     public static native long getTime(long ssl);
385 
386     /**
387      * SSL_get_timeout
388      * @param ssl the SSL instance (SSL *)
389      * @return returns the timeout for the session ssl The time is given in seconds since the Epoch
390      */
391     public static native long getTimeout(long ssl);
392 
393     /**
394      * SSL_set_timeout
395      * @param ssl the SSL instance (SSL *)
396      * @param seconds timeout in seconds
397      * @return returns the timeout for the session ssl before this call. The time is given in seconds since the Epoch
398      */
399     public static native long setTimeout(long ssl, long seconds);
400 
401     /**
402      * Set Type of Client Certificate verification and Maximum depth of CA Certificates
403      * in Client Certificate verification.
404      * <p>
405      * This directive sets the Certificate verification level for the Client
406      * Authentication. Notice that this directive can be used both in per-server
407      * and per-directory context. In per-server context it applies to the client
408      * authentication process used in the standard SSL handshake when a connection
409      * is established. In per-directory context it forces a SSL renegotiation with
410      * the reconfigured client verification level after the HTTP request was read
411      * but before the HTTP response is sent.
412      * <p>
413      * The following levels are available for level:
414      * <ul>
415      * <li>{@link #SSL_CVERIFY_IGNORED} - The level is ignored. Only depth will change.</li>
416      * <li>{@link #SSL_CVERIFY_NONE} - No client Certificate is required at all</li>
417      * <li>{@link #SSL_CVERIFY_OPTIONAL} - The client may present a valid Certificate</li>
418      * <li>{@link #SSL_CVERIFY_REQUIRED} - The client has to present a valid Certificate</li>
419      * </ul>
420      * The depth actually is the maximum number of intermediate certificate issuers,
421      * i.e. the number of CA certificates which are max allowed to be followed while
422      * verifying the client certificate. A depth of 0 means that self-signed client
423      * certificates are accepted only, the default depth of 1 means the client
424      * certificate can be self-signed or has to be signed by a CA which is directly
425      * known to the server (i.e. the CA's certificate is under
426      * {@code setCACertificatePath}, etc.
427      *
428      * @param ssl the SSL instance (SSL *)
429      * @param level Type of Client Certificate verification.
430      * @param depth Maximum depth of CA Certificates in Client Certificate
431      *              verification. Ignored if value is {@code <0}.
432      */
433     public static native void setVerify(long ssl, int level, int depth);
434 
435     /**
436      * Set OpenSSL Option.
437      * @param ssl the SSL instance (SSL *)
438      * @param options  See SSL.SSL_OP_* for option flags.
439      */
440     public static native void setOptions(long ssl, int options);
441 
442     /**
443      * Clear OpenSSL Option.
444      * @param ssl the SSL instance (SSL *)
445      * @param options  See SSL.SSL_OP_* for option flags.
446      */
447     public static native void clearOptions(long ssl, int options);
448 
449     /**
450      * Get OpenSSL Option.
451      * @param ssl the SSL instance (SSL *)
452      * @return options  See SSL.SSL_OP_* for option flags.
453      */
454     public static native int getOptions(long ssl);
455 
456     /**
457      * Call SSL_set_mode
458      *
459      * @param ssl the SSL instance (SSL *).
460      * @param mode the mode
461      * @return the set mode.
462      */
463     public static native int setMode(long ssl, int mode);
464 
465     /**
466      * Call SSL_get_mode
467      *
468      * @param ssl the SSL instance (SSL *).
469      * @return the mode.
470      */
471     public static native int getMode(long ssl);
472 
473     /**
474      * Get the maximum overhead, in bytes, of wrapping (a.k.a sealing) a record with ssl.
475      * See <a href="https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_max_seal_overhead">SSL_max_seal_overhead</a>.
476      * @param ssl the SSL instance (SSL *).
477      * @return Maximum overhead, in bytes, of wrapping (a.k.a sealing) a record with ssl.
478      */
479     public static native int getMaxWrapOverhead(long ssl);
480 
481     /**
482      * Returns all Returns the cipher suites that are available for negotiation in an SSL handshake.
483      * @param ssl the SSL instance (SSL *)
484      * @return ciphers
485      */
486     public static native String[] getCiphers(long ssl);
487 
488     /**
489      * Returns the cipher suites available for negotiation in SSL handshake.
490      * <p>
491      * This complex directive uses a colon-separated cipher-spec string consisting
492      * of OpenSSL cipher specifications to configure the Cipher Suite the client
493      * is permitted to negotiate in the SSL handshake phase. Notice that this
494      * directive can be used both in per-server and per-directory context.
495      * In per-server context it applies to the standard SSL handshake when a
496      * connection is established. In per-directory context it forces a SSL
497      * renegotiation with the reconfigured Cipher Suite after the HTTP request
498      * was read but before the HTTP response is sent.
499      * @param ssl the SSL instance (SSL *)
500      * @param ciphers an SSL cipher specification
501      * @return {@code true} if successful
502      * @throws Exception if an error happened
503      */
504     public static native boolean setCipherSuites(long ssl, String ciphers)
505             throws Exception;
506 
507     /**
508      * Returns the ID of the session as byte array representation.
509      *
510      * @param ssl the SSL instance (SSL *)
511      * @return the session as byte array representation obtained via SSL_SESSION_get_id.
512      */
513     public static native byte[] getSessionId(long ssl);
514 
515     /**
516      * Returns the number of handshakes done for this SSL instance. This also includes renegations.
517      *
518      * @param ssl the SSL instance (SSL *)
519      * @return the number of handshakes done for this SSL instance.
520      */
521     public static native int getHandshakeCount(long ssl);
522 
523     /**
524      * Clear all the errors from the error queue that OpenSSL encountered on this thread.
525      */
526     public static native void clearError();
527 
528     /**
529      * Call SSL_set_tlsext_host_name
530      *
531      * @param ssl the SSL instance (SSL *)
532      * @param hostname the hostname
533      */
534     public static native void setTlsExtHostName(long ssl, String hostname);
535 
536     /**
537      * Explicitly control <a href="https://wiki.openssl.org/index.php/Hostname_validation">hostname validation</a>
538      * <a href="https://www.openssl.org/docs/man1.0.2/crypto/X509_check_host.html">see X509_check_host for X509_CHECK_FLAG* definitions</a>.
539      * Values are defined as a bitmask of {@code X509_CHECK_FLAG*} values.
540      * @param ssl the SSL instance (SSL*).
541      * @param flags a bitmask of {@code X509_CHECK_FLAG*} values.
542      * @param hostname the hostname which is expected for validation.
543      */
544     public static native void setHostNameValidation(long ssl, int flags, String hostname);
545 
546     /**
547      * Return the methods used for authentication.
548      *
549      * @param ssl the SSL instance (SSL*)
550      * @return the methods
551      */
552     public static native String[] authenticationMethods(long ssl);
553 
554     /**
555      * Set BIO of PEM-encoded Server CA Certificates
556      * <p>
557      * This directive sets the optional all-in-one file where you can assemble the
558      * certificates of Certification Authorities (CA) which form the certificate
559      * chain of the server certificate. This starts with the issuing CA certificate
560      * of the server certificate and can range up to the root CA certificate.
561      * Such a file is simply the concatenation of the various PEM-encoded CA
562      * Certificate files, usually in certificate chain order.
563      * <p>
564      * But be careful: Providing the certificate chain works only if you are using
565      * a single (either RSA or DSA) based server certificate. If you are using a
566      * coupled RSA+DSA certificate pair, this will work only if actually both
567      * certificates use the same certificate chain. Otherwsie the browsers will be
568      * confused in this situation.
569      * @param ssl Server or Client to use.
570      * @param bio BIO of PEM-encoded Server CA Certificates.
571      * @param skipfirst Skip first certificate if chain file is inside
572      *                  certificate file.
573      */
574     public static native void setCertificateChainBio(long ssl, long bio, boolean skipfirst);
575 
576     /**
577      * Set Certificate
578      * <br>
579      * Point setCertificate at a PEM encoded certificate stored in a BIO. If
580      * the certificate is encrypted, then you will be prompted for a
581      * pass phrase.  Note that a kill -HUP will prompt again. A test
582      * certificate can be generated with `make certificate' under
583      * built time. Keep in mind that if you've both a RSA and a DSA
584      * certificate you can configure both in parallel (to also allow
585      * the use of DSA ciphers, etc.)
586      * <br>
587      * If the key is not combined with the certificate, use key param
588      * to point at the key file.  Keep in mind that if
589      * you've both a RSA and a DSA private key you can configure
590      * both in parallel (to also allow the use of DSA ciphers, etc.)
591      * @param ssl Server or Client to use.
592      * @param certBio Certificate BIO.
593      * @param keyBio Private Key BIO to use if not in cert.
594      * @param password Certificate password. If null and certificate
595      *                 is encrypted.
596      * @throws Exception if an error happened
597      */
598     public static native void setCertificateBio(
599             long ssl, long certBio, long keyBio, String password) throws Exception;
600 
601     /**
602      * Load a private key from the used OpenSSL ENGINE via the
603      * <a href="https://www.openssl.org/docs/man1.1.0/crypto/ENGINE_load_private_key.html">ENGINE_load_private_key</a>
604      * function.
605      *
606      * <p>Be sure you understand how OpenSsl will behave with respect to reference counting!
607      *
608      * If the ownership is not transferred you need to call {@link #freePrivateKey(long)} once the key is not used
609      * anymore to prevent memory leaks.
610      *
611      * @param keyId the id of the key.
612      * @param password the password to use or {@code null} if none.
613      * @return {@code EVP_PKEY} pointer
614      * @throws Exception if an error happened
615      */
616     public static native long loadPrivateKeyFromEngine(String keyId, String password) throws Exception;
617 
618     /**
619      * Parse private key from BIO and return {@code EVP_PKEY} pointer.
620      *
621      * <p>Be sure you understand how OpenSsl will behave with respect to reference counting!
622      *
623      * If the {@code EVP_PKEY} pointer is used with the client certificate callback
624      * {@link CertificateRequestedCallback} the ownership goes over to OpenSsl / Tcnative and so calling
625      * {@link #freePrivateKey(long)} should <strong>NOT</strong> be done in this case. Otherwise you may
626      * need to call {@link #freePrivateKey(long)} to decrement the reference count and free memory.
627      *
628      * @param privateKeyBio the pointer to the {@code BIO} that contains the private key
629      * @param password the password or {@code null} if no password is needed
630      * @return {@code EVP_PKEY} pointer
631      * @throws Exception if an error happened
632      */
633     public static native long parsePrivateKey(long privateKeyBio, String password) throws Exception;
634 
635     /**
636      * Free private key ({@code EVP_PKEY} pointer).
637      *
638      * @param privateKey {@code EVP_PKEY} pointer
639      */
640     public static native void freePrivateKey(long privateKey);
641 
642     /**
643      * Parse X509 chain from BIO and return ({@code STACK_OF(X509)} pointer).
644      *
645      * <p>Be sure you understand how OpenSsl will behave with respect to reference counting!
646      *
647      * If the {@code STACK_OF(X509)} pointer is used with the client certificate callback
648      * {@link CertificateRequestedCallback} the ownership goes over to OpenSsl / Tcnative and so calling
649      * {@link #freeX509Chain(long)} should <strong>NOT</strong> be done in this case. Otherwise you may
650      * need to call {@link #freeX509Chain(long)} to decrement the reference count and free memory.
651      *
652      * @param x509ChainBio the pointer to the {@code BIO} that contains the X509 chain
653      * @return {@code STACK_OF(X509)} pointer
654      * @throws Exception if an error happened
655      */
656     public static native long parseX509Chain(long x509ChainBio) throws Exception;
657 
658     /**
659      * Free x509 chain ({@code STACK_OF(X509)} pointer).
660      *
661      * @param x509Chain {@code STACK_OF(X509)} pointer
662      */
663     public static native void freeX509Chain(long x509Chain);
664     
665     /**
666      * Enables OCSP stapling for the given {@link SSLEngine} or throws an
667      * exception if OCSP stapling is not supported.
668      * 
669      * <p>NOTE: This needs to happen before the SSL handshake.
670      * 
671      * <p><a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html">SSL_set_tlsext_status_type</a>
672      * <p><a href="https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html">Search for OCSP</a>
673      */
674     public static native void enableOcsp(long ssl);
675 
676     /**
677      * Sets the keymaterial to be used for the server side. The passed in chain and key needs to be generated via
678      * {@link #parseX509Chain(long)} and {@link #parsePrivateKey(long, String)}. It's important to note that the caller
679      * of the method is responsible to free the passed in chain and key in any case as this method will increment the
680      * reference count of the chain and key.
681      */
682     public static native void setKeyMaterialServerSide(long ssl, long chain, long key) throws Exception;
683 
684     /**
685      * Sets the keymaterial to be used for the client side. The passed in chain and key needs to be generated via
686      * {@link #parseX509Chain(long)} and {@link #parsePrivateKey(long, String)}. It's important to note that the caller
687      * of the method is responsible to free the passed in chain and key in any case as this method will increment the
688      * reference count of the chain and key.
689      */
690     public static native void setKeyMaterialClientSide(long ssl, long x509Out, long pkeyOut, long chain, long key) throws Exception;
691 
692     /**
693      * Sets the OCSP response for the given {@link SSLEngine} or throws an
694      * exception in case of an error.
695      *
696      * <p>NOTE: This is only meant to be called for server {@link SSLEngine}s.
697      *
698      * <p><a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html">SSL_set_tlsext_status_type</a>
699      * <p><a href="https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html">Search for OCSP</a>
700      *
701      * @param ssl the SSL instance (SSL *)
702      */
703     public static native void setOcspResponse(long ssl, byte[] response);
704 
705     /**
706      * Returns the OCSP response for the given {@link SSLEngine} or {@code null}
707      * if the server didn't provide a stapled OCSP response.
708      *
709      * <p>NOTE: This is only meant to be called for client {@link SSLEngine}s.
710      *
711      * <p><a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html">SSL_set_tlsext_status_type</a>
712      * <p><a href="https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html">Search for OCSP</a>
713      *
714      * @param ssl the SSL instance (SSL *)
715      */
716     public static native byte[] getOcspResponse(long ssl);
717 
718     /**
719      * Set the FIPS mode to use. See <a href="https://wiki.openssl.org/index.php/FIPS_mode_set()"> man FIPS_mode_set</a>.
720      *
721      * @param mode the mode to use.
722      * @throws Exception throws if setting the fips mode failed.
723      */
724     public static native void fipsModeSet(int mode) throws Exception;
725 }