Class SSL


  • public final class SSL
    extends Object
    SSL
    Author:
    Mladen Turk
    • Constructor Detail

      • SSL

        public SSL()
    • Method Detail

      • version

        public static int version()
      • versionString

        public static String versionString()
      • initialize

        public static int initialize​(String engine)
        Initialize OpenSSL support. This function needs to be called once for the lifetime of JVM. Library.init() has to be called before.
        Parameters:
        engine - Support for external a Crypto Device ("engine"), usually a hardware accelerator card for crypto operations.
        Returns:
        APR status code
      • fipsModeGet

        public static int fipsModeGet()
                               throws Exception
        Get the status of FIPS Mode.
        Returns:
        FIPS_mode return code. It is 0 if OpenSSL is not in FIPS mode, 1 if OpenSSL is in FIPS Mode.
        Throws:
        Exception - If tcnative was not compiled with FIPS Mode available.
        See Also:
        OpenSSL method FIPS_mode()
      • fipsModeSet

        public static int fipsModeSet​(int mode)
                               throws Exception
        Enable/Disable FIPS Mode.
        Parameters:
        mode - 1 - enable, 0 - disable
        Returns:
        FIPS_mode_set return code
        Throws:
        Exception - If tcnative was not compiled with FIPS Mode available, or if FIPS_mode_set() call returned an error value.
        See Also:
        OpenSSL method FIPS_mode_set()
      • randLoad

        public static boolean randLoad​(String filename)
        Add content of the file to the PRNG
        Parameters:
        filename - Filename containing random data. If null the default file will be tested. The seed file is $RANDFILE if that environment variable is set, $HOME/.rnd otherwise. In case both files are unavailable builtin random seed generator is used.
      • randSave

        public static boolean randSave​(String filename)
        Writes a number of random bytes (currently 1024) to file filename which can be used to initialize the PRNG by calling randLoad in a later session.
        Parameters:
        filename - Filename to save the data
      • randMake

        public static boolean randMake​(String filename,
                                       int len,
                                       boolean base64)
        Creates random data to filename
        Parameters:
        filename - Filename to save the data
        len - The length of random sequence in bytes
        base64 - Output the data in Base64 encoded format
      • randSet

        public static void randSet​(String filename)
        Sets global random filename.
        Parameters:
        filename - Filename to use. If set it will be used for SSL initialization and all contexts where explicitly not set.
      • newBIO

        public static long newBIO​(long pool,
                                  BIOCallback callback)
                           throws Exception
        Initialize new BIO
        Parameters:
        pool - The pool to use.
        callback - BIOCallback to use
        Returns:
        new BIO handle
        Throws:
        Exception
      • newMemBIO

        public static long newMemBIO()
                              throws Exception
        Initialize new in-memory BIO that is located in the secure heap.
        Returns:
        New BIO handle
        Throws:
        Exception
      • closeBIO

        public static int closeBIO​(long bio)
        Close BIO and dereference callback object
        Parameters:
        bio - BIO to close and destroy.
        Returns:
        APR Status code
      • setPasswordCallback

        public static void setPasswordCallback​(PasswordCallback callback)
        Set global Password callback for obtaining passwords.
        Parameters:
        callback - PasswordCallback implementation to use.
      • setPassword

        public static void setPassword​(String password)
        Set global Password for decrypting certificates and keys.
        Parameters:
        password - Password to use.
      • generateRSATempKey

        public static boolean generateRSATempKey​(int idx)
        Generate temporary RSA key.
        Index can be one of:
         SSL_TMP_KEY_RSA_512
         SSL_TMP_KEY_RSA_1024
         SSL_TMP_KEY_RSA_2048
         SSL_TMP_KEY_RSA_4096
         
        By default 512 and 1024 keys are generated on startup. You can use a low priority thread to generate them on the fly.
        Parameters:
        idx - temporary key index.
      • loadDSATempKey

        public static boolean loadDSATempKey​(int idx,
                                             String file)
        Load temporary DSA key from file
        Index can be one of:
         SSL_TMP_KEY_DH_512
         SSL_TMP_KEY_DH_1024
         SSL_TMP_KEY_DH_2048
         SSL_TMP_KEY_DH_4096
         
        Parameters:
        idx - temporary key index.
        file - File containing DH params.
      • getLastError

        public static String getLastError()
        Return last SSL error string
      • hasOp

        public static boolean hasOp​(int op)
        Return true if all the requested SSL_OP_* are supported by OpenSSL. Note that for versions of tcnative < 1.1.25, this method will return true if and only if op= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION and tcnative supports that flag.
        Parameters:
        op - Bitwise-OR of all SSL_OP_* to test.
        Returns:
        true if all SSL_OP_* are supported by OpenSSL library.
      • newSSL

        public static long newSSL​(long ctx,
                                  boolean server)
        SSL_new
        Parameters:
        ctx - Server or Client context to use.
        server - if true configure SSL instance to use accept handshake routines if false configure SSL instance to use connect handshake routines
        Returns:
        pointer to SSL instance (SSL *)
      • setBIO

        public static void setBIO​(long ssl,
                                  long rbio,
                                  long wbio)
        SSL_set_bio
        Parameters:
        ssl - SSL pointer (SSL *)
        rbio - read BIO pointer (BIO *)
        wbio - write BIO pointer (BIO *)
      • getError

        public static int getError​(long ssl,
                                   int ret)
        SSL_get_error
        Parameters:
        ssl - SSL pointer (SSL *)
        ret - TLS/SSL I/O return value
      • pendingWrittenBytesInBIO

        public static int pendingWrittenBytesInBIO​(long bio)
        BIO_ctrl_pending
        Parameters:
        bio - BIO pointer (BIO *)
        Returns:
      • pendingReadableBytesInSSL

        public static int pendingReadableBytesInSSL​(long ssl)
        SSL_pending
        Parameters:
        ssl - SSL pointer (SSL *)
        Returns:
      • writeToBIO

        public static int writeToBIO​(long bio,
                                     long wbuf,
                                     int wlen)
        BIO_write
        Parameters:
        bio -
        wbuf -
        wlen -
        Returns:
      • readFromBIO

        public static int readFromBIO​(long bio,
                                      long rbuf,
                                      int rlen)
        BIO_read
        Parameters:
        bio -
        rbuf -
        rlen -
        Returns:
      • shouldRetryBIO

        public static boolean shouldRetryBIO​(long bio)
        BIO_should_retry
        Parameters:
        bio - the BIO.
        Returns:
        true if the failed BIO operation should be retried later.
      • writeToSSL

        public static int writeToSSL​(long ssl,
                                     long wbuf,
                                     int wlen)
        SSL_write
        Parameters:
        ssl - the SSL instance (SSL *)
        wbuf -
        wlen -
        Returns:
      • readFromSSL

        public static int readFromSSL​(long ssl,
                                      long rbuf,
                                      int rlen)
        SSL_read
        Parameters:
        ssl - the SSL instance (SSL *)
        rbuf -
        rlen -
        Returns:
      • getShutdown

        public static int getShutdown​(long ssl)
        SSL_get_shutdown
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • setShutdown

        public static void setShutdown​(long ssl,
                                       int mode)
        SSL_set_shutdown
        Parameters:
        ssl - the SSL instance (SSL *)
        mode -
      • freeSSL

        public static void freeSSL​(long ssl)
        SSL_free
        Parameters:
        ssl - the SSL instance (SSL *)
      • makeNetworkBIO

        public static long makeNetworkBIO​(long ssl)
        Creates a BIO with the default max BIO size.
        See Also:
        makeNetworkBIO(long, int)
      • makeNetworkBIO

        public static long makeNetworkBIO​(long ssl,
                                          int maxBioSize)
        Creates a BIO with the given max BIO size.
        See Also:
        makeNetworkBIO(long, int, int)
      • makeNetworkBIO

        public static long makeNetworkBIO​(long ssl,
                                          int maxInternalBIOSize,
                                          int maxNetworkBIOSize)
        Wire up internal and network BIOs for the given SSL instance. Warning: you must explicitly free this resource by calling freeBIO While the SSL's internal/application data BIO will be freed when freeSSL is called on the provided SSL instance, you must call freeBIO on the returned network BIO. Please see man BIO_s_bio (example section) for more details.
        Parameters:
        ssl - the SSL instance (SSL *)
        maxInternalBIOSize - The maximum size of the application side BIO. Pass 0 to use the default max size.
        maxNetworkBIOSize - The maximum size of the network side BIO. Pass 0 to use the default max size.
        Returns:
        pointer to the Network BIO (BIO *)
      • freeBIO

        public static void freeBIO​(long bio)
        BIO_free
        Parameters:
        bio -
      • flushBIO

        public static void flushBIO​(long bio)
        BIO_flush
        Parameters:
        bio -
      • shutdownSSL

        public static int shutdownSSL​(long ssl)
        SSL_shutdown
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • getLastErrorNumber

        public static int getLastErrorNumber()
        Get the error number representing the last error OpenSSL encountered on this thread.
        Returns:
      • getCipherForSSL

        public static String getCipherForSSL​(long ssl)
        SSL_get_cipher
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • getVersion

        public static String getVersion​(long ssl)
        SSL_get_version
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • doHandshake

        public static int doHandshake​(long ssl)
        SSL_do_handshake
        Parameters:
        ssl - the SSL instance (SSL *)
      • isInInit

        public static int isInInit​(long SSL)
        SSL_in_init
        Parameters:
        SSL -
        Returns:
      • getNextProtoNegotiated

        public static String getNextProtoNegotiated​(long ssl)
        SSL_get0_next_proto_negotiated
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • getAlpnSelected

        public static String getAlpnSelected​(long ssl)
        SSL_get0_alpn_selected
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
      • getPeerCertChain

        public static byte[][] getPeerCertChain​(long ssl)
        Get the peer certificate chain or null if non was send.
      • getPeerCertificate

        public static byte[] getPeerCertificate​(long ssl)
        Get the peer certificate or null if non was send.
      • getErrorString

        public static String getErrorString​(long errorNumber)
      • getTime

        public static long getTime​(long ssl)
        SSL_get_time
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        returns the time at which the session ssl was established. The time is given in seconds since the Epoch
      • getTimeout

        public static long getTimeout​(long ssl)
        SSL_get_timeout
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        returns the timeout for the session ssl The time is given in seconds since the Epoch
      • setTimeout

        public static long setTimeout​(long ssl,
                                      long seconds)
        SSL_set_timeout
        Parameters:
        ssl - the SSL instance (SSL *)
        seconds - timeout in seconds
        Returns:
        returns the timeout for the session ssl before this call. The time is given in seconds since the Epoch
      • setVerify

        public static void setVerify​(long ssl,
                                     int level,
                                     int depth)
        Set Type of Client Certificate verification and Maximum depth of CA Certificates in Client Certificate verification.
        This directive sets the Certificate verification level for the Client Authentication. Notice that this directive can be used both in per-server and per-directory context. In per-server context it applies to the client authentication process used in the standard SSL handshake when a connection is established. In per-directory context it forces a SSL renegotiation with the reconfigured client verification level after the HTTP request was read but before the HTTP response is sent.
        The following levels are available for level:
         SSL_CVERIFY_NONE           - No client Certificate is required at all
         SSL_CVERIFY_OPTIONAL       - The client may present a valid Certificate
         SSL_CVERIFY_REQUIRE        - The client has to present a valid Certificate
         SSL_CVERIFY_OPTIONAL_NO_CA - The client may present a valid Certificate
                                      but it need not to be (successfully) verifiable
         

        The depth actually is the maximum number of intermediate certificate issuers, i.e. the number of CA certificates which are max allowed to be followed while verifying the client certificate. A depth of 0 means that self-signed client certificates are accepted only, the default depth of 1 means the client certificate can be self-signed or has to be signed by a CA which is directly known to the server (i.e. the CA's certificate is under setCACertificatePath, etc.
        Parameters:
        ssl - the SSL instance (SSL *)
        level - Type of Client Certificate verification.
        depth - Maximum depth of CA Certificates in Client Certificate verification.
      • setOptions

        public static void setOptions​(long ssl,
                                      int options)
        Set OpenSSL Option.
        Parameters:
        ssl - the SSL instance (SSL *)
        options - See SSL.SSL_OP_* for option flags.
      • clearOptions

        public static void clearOptions​(long ssl,
                                        int options)
        Clear OpenSSL Option.
        Parameters:
        ssl - the SSL instance (SSL *)
        options - See SSL.SSL_OP_* for option flags.
      • getOptions

        public static int getOptions​(long ssl)
        Get OpenSSL Option.
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        options See SSL.SSL_OP_* for option flags.
      • getCiphers

        public static String[] getCiphers​(long ssl)
        Returns all Returns the cipher suites that are available for negotiation in an SSL handshake.
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        ciphers
      • setCipherSuites

        public static boolean setCipherSuites​(long ssl,
                                              String ciphers)
                                       throws Exception
        Returns the cipher suites available for negotiation in SSL handshake.
        This complex directive uses a colon-separated cipher-spec string consisting of OpenSSL cipher specifications to configure the Cipher Suite the client is permitted to negotiate in the SSL handshake phase. Notice that this directive can be used both in per-server and per-directory context. In per-server context it applies to the standard SSL handshake when a connection is established. In per-directory context it forces a SSL renegotiation with the reconfigured Cipher Suite after the HTTP request was read but before the HTTP response is sent.
        Parameters:
        ssl - the SSL instance (SSL *)
        ciphers - an SSL cipher specification
        Throws:
        Exception
      • getSessionId

        public static byte[] getSessionId​(long ssl)
        Returns the ID of the session as byte array representation.
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        the session as byte array representation obtained via SSL_SESSION_get_id.
      • getHandshakeCount

        public static int getHandshakeCount​(long ssl)
        Returns the number of handshakes done for this SSL instance. This also includes renegations.
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        the number of handshakes done for this SSL instance.
      • clearError

        public static void clearError()
        Clear all the errors from the error queue that OpenSSL encountered on this thread.
      • renegotiate

        public static int renegotiate​(long ssl)
        Call SSL_renegotiate.
        Parameters:
        ssl - the SSL instance (SSL *)
        Returns:
        the result of the operation
      • setState

        public static void setState​(long ssl,
                                    int state)
        Call SSL_set_state.
        Parameters:
        ssl - the SSL instance (SSL *)
      • setTlsExtHostName

        public static void setTlsExtHostName​(long ssl,
                                             String hostname)
        Call SSL_set_tlsext_host_name
        Parameters:
        ssl - the SSL instance (SSL *)
        hostname - the hostname
      • authenticationMethods

        public static String[] authenticationMethods​(long ssl)
      • setCertificateChainBio

        public static void setCertificateChainBio​(long ssl,
                                                  long bio,
                                                  boolean skipfirst)
        Set BIO of PEM-encoded Server CA Certificates

        This directive sets the optional all-in-one file where you can assemble the certificates of Certification Authorities (CA) which form the certificate chain of the server certificate. This starts with the issuing CA certificate of of the server certificate and can range up to the root CA certificate. Such a file is simply the concatenation of the various PEM-encoded CA Certificate files, usually in certificate chain order.

        But be careful: Providing the certificate chain works only if you are using a single (either RSA or DSA) based server certificate. If you are using a coupled RSA+DSA certificate pair, this will work only if actually both certificates use the same certificate chain. Otherwsie the browsers will be confused in this situation.

        Parameters:
        ssl - Server or Client to use.
        bio - BIO of PEM-encoded Server CA Certificates.
        skipfirst - Skip first certificate if chain file is inside certificate file.
      • setCertificateBio

        public static void setCertificateBio​(long ssl,
                                             long certBio,
                                             long keyBio,
                                             String password)
                                      throws Exception
        Set Certificate
        Point setCertificate at a PEM encoded certificate stored in a BIO. If the certificate is encrypted, then you will be prompted for a pass phrase. Note that a kill -HUP will prompt again. A test certificate can be generated with `make certificate' under built time. Keep in mind that if you've both a RSA and a DSA certificate you can configure both in parallel (to also allow the use of DSA ciphers, etc.)
        If the key is not combined with the certificate, use key param to point at the key file. Keep in mind that if you've both a RSA and a DSA private key you can configure both in parallel (to also allow the use of DSA ciphers, etc.)
        Parameters:
        ssl - Server or Client to use.
        certBio - Certificate BIO.
        keyBio - Private Key BIO to use if not in cert.
        password - Certificate password. If null and certificate is encrypted.
        Throws:
        Exception
      • parsePrivateKey

        public static long parsePrivateKey​(long privateKeyBio,
                                           String password)
                                    throws Exception
        Parse private key from BIO and return EVP_PKEY pointer.

        Be sure you understand how OpenSsl will behave with respect to reference counting! If the EVP_PKEY pointer is used with the client certificate callback CertificateRequestedCallback the ownership goes over to OpenSsl / Tcnative and so calling freePrivateKey(long) should NOT be done in this case. Otherwise you may need to call freePrivateKey(long) to decrement the reference count and free memory.

        Throws:
        Exception
      • freePrivateKey

        public static void freePrivateKey​(long privateKey)
        Free private key (EVP_PKEY pointer).
      • parseX509Chain

        public static long parseX509Chain​(long x509ChainBio)
                                   throws Exception
        Parse X509 chain from BIO and return (STACK_OF(X509) pointer).

        Be sure you understand how OpenSsl will behave with respect to reference counting! If the STACK_OF(X509) pointer is used with the client certificate callback CertificateRequestedCallback the ownership goes over to OpenSsl / Tcnative and and so calling freeX509Chain(long) should NOT be done in this case. Otherwise you may need to call freeX509Chain(long) to decrement the reference count and free memory.

        Throws:
        Exception
      • freeX509Chain

        public static void freeX509Chain​(long x509Chain)
        Free x509 chain (STACK_OF(X509) pointer).