Search in sources :

Example 11 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project XobotOS by xamarin.

the class ServerHandshakeImpl method processClientHello.

/**
     *
     * Processes Client Hello message.
     * Server responds to client hello message with server hello
     * and (if necessary) server certificate, server key exchange,
     * certificate request, and server hello done messages.
     */
void processClientHello() {
    CipherSuite cipher_suite;
    // check that clientHello contains CompressionMethod.null
    checkCompression: {
        for (int i = 0; i < clientHello.compression_methods.length; i++) {
            if (clientHello.compression_methods[i] == 0) {
                break checkCompression;
            }
        }
        fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
    }
    if (!ProtocolVersion.isSupported(clientHello.client_version)) {
        fatalAlert(AlertProtocol.PROTOCOL_VERSION, "PROTOCOL VERSION. Unsupported client version " + clientHello.client_version[0] + clientHello.client_version[1]);
    }
    isResuming = false;
    FIND: if (clientHello.session_id.length != 0) {
        // client wishes to reuse session
        SSLSessionImpl sessionToResume;
        boolean reuseCurrent = false;
        // reuse current session
        if (session != null && Arrays.equals(session.id, clientHello.session_id)) {
            if (session.isValid()) {
                isResuming = true;
                break FIND;
            }
            reuseCurrent = true;
        }
        // find session in cash
        sessionToResume = findSessionToResume(clientHello.session_id);
        if (sessionToResume == null || !sessionToResume.isValid()) {
            if (!parameters.getEnableSessionCreation()) {
                if (reuseCurrent) {
                    // we can continue current session
                    sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
                    status = NOT_HANDSHAKING;
                    clearMessages();
                    return;
                }
                // throw AlertException
                fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
            }
            session = null;
        } else {
            session = (SSLSessionImpl) sessionToResume.clone();
            isResuming = true;
        }
    }
    if (isResuming) {
        cipher_suite = session.cipherSuite;
        // clientHello.cipher_suites must include at least cipher_suite from the session
        checkCipherSuite: {
            for (int i = 0; i < clientHello.cipher_suites.length; i++) {
                if (cipher_suite.equals(clientHello.cipher_suites[i])) {
                    break checkCipherSuite;
                }
            }
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
        }
    } else {
        cipher_suite = selectSuite(clientHello.cipher_suites);
        if (cipher_suite == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
        }
        if (!parameters.getEnableSessionCreation()) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
        }
        session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
        if (engineOwner != null) {
            session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
        } else {
            session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
        }
    }
    recordProtocol.setVersion(clientHello.client_version);
    session.protocol = ProtocolVersion.getByVersion(clientHello.client_version);
    session.clientRandom = clientHello.random;
    // create server hello message
    serverHello = new ServerHello(parameters.getSecureRandom(), clientHello.client_version, session.getId(), cipher_suite, //CompressionMethod.null
    (byte) 0);
    session.serverRandom = serverHello.random;
    send(serverHello);
    if (isResuming) {
        sendChangeCipherSpec();
        return;
    }
    //    create and send server certificate message if needed
    if (!cipher_suite.isAnonymous()) {
        // need to send server certificate
        X509Certificate[] certs = null;
        String certType = cipher_suite.getServerKeyType();
        if (certType == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO CERT TYPE FOR " + cipher_suite.getName());
        }
        // obtain certificates from key manager
        String alias = null;
        X509KeyManager km = parameters.getKeyManager();
        if (km instanceof X509ExtendedKeyManager) {
            X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
            if (this.socketOwner != null) {
                alias = ekm.chooseServerAlias(certType, null, this.socketOwner);
            } else {
                alias = ekm.chooseEngineServerAlias(certType, null, this.engineOwner);
            }
            if (alias != null) {
                certs = ekm.getCertificateChain(alias);
            }
        } else {
            alias = km.chooseServerAlias(certType, null, this.socketOwner);
            if (alias != null) {
                certs = km.getCertificateChain(alias);
            }
        }
        if (certs == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
            return;
        }
        session.localCertificates = certs;
        serverCert = new CertificateMessage(certs);
        privKey = km.getPrivateKey(alias);
        send(serverCert);
    }
    // create and send server key exchange message if needed
    RSAPublicKey rsakey = null;
    DHPublicKeySpec dhkeySpec = null;
    byte[] hash = null;
    BigInteger p = null;
    BigInteger g = null;
    KeyPairGenerator kpg = null;
    try {
        if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
            PublicKey pk = serverCert.certs[0].getPublicKey();
            if (getRSAKeyLength(pk) > 512) {
                // key is longer than 512 bits
                kpg = KeyPairGenerator.getInstance("RSA");
                kpg.initialize(512);
            }
        } else if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
            kpg = KeyPairGenerator.getInstance("DH");
            p = new BigInteger(1, DHParameters.getPrime());
            g = new BigInteger("2");
            DHParameterSpec spec = new DHParameterSpec(p, g);
            kpg.initialize(spec);
        }
    } catch (Exception e) {
        fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
    }
    if (kpg != null) {
        // need to send server key exchange message
        DigitalSignature ds = new DigitalSignature(cipher_suite.authType);
        KeyPair kp = null;
        try {
            kp = kpg.genKeyPair();
            if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                rsakey = (RSAPublicKey) kp.getPublic();
            } else {
                DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
                KeyFactory kf = KeyFactory.getInstance("DH");
                dhkeySpec = kf.getKeySpec(dhkey, DHPublicKeySpec.class);
            }
            if (!cipher_suite.isAnonymous()) {
                // calculate signed_params
                // init by private key which correspond to
                // server certificate
                ds.init(privKey);
                // use emphemeral key for key exchange
                privKey = kp.getPrivate();
                ds.update(clientHello.getRandom());
                ds.update(serverHello.getRandom());
                byte[] tmp;
                byte[] tmpLength = new byte[2];
                //FIXME 1_byte==0x00
                if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                    tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getModulus());
                    tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
                    tmpLength[1] = (byte) (tmp.length & 0xFF);
                    ds.update(tmpLength);
                    ds.update(tmp);
                    tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getPublicExponent());
                    tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
                    tmpLength[1] = (byte) (tmp.length & 0xFF);
                    ds.update(tmpLength);
                    ds.update(tmp);
                } else {
                    tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getP());
                    tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
                    tmpLength[1] = (byte) (tmp.length & 0xFF);
                    ds.update(tmpLength);
                    ds.update(tmp);
                    tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getG());
                    tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
                    tmpLength[1] = (byte) (tmp.length & 0xFF);
                    ds.update(tmpLength);
                    ds.update(tmp);
                    tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getY());
                    tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
                    tmpLength[1] = (byte) (tmp.length & 0xFF);
                    ds.update(tmpLength);
                    ds.update(tmp);
                }
                hash = ds.sign();
            } else {
                // use emphemeral key for key exchange
                privKey = kp.getPrivate();
            }
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
        }
        if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
            serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(), rsakey.getPublicExponent(), null, hash);
        } else {
            serverKeyExchange = new ServerKeyExchange(p, g, dhkeySpec.getY(), hash);
        }
        send(serverKeyExchange);
    }
    // CERTIFICATE_REQUEST
    certRequest: if (parameters.getWantClientAuth() || parameters.getNeedClientAuth()) {
        X509Certificate[] accepted;
        try {
            X509TrustManager tm = parameters.getTrustManager();
            accepted = tm.getAcceptedIssuers();
        } catch (ClassCastException e) {
            // don't send certificateRequest
            break certRequest;
        }
        byte[] requestedClientCertTypes = { CipherSuite.TLS_CT_RSA_SIGN, CipherSuite.TLS_CT_DSS_SIGN };
        certificateRequest = new CertificateRequest(requestedClientCertTypes, accepted);
        send(certificateRequest);
    }
    // SERVER_HELLO_DONE
    serverHelloDone = new ServerHelloDone();
    send(serverHelloDone);
    status = NEED_UNWRAP;
}
Also used : DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509KeyManager(javax.net.ssl.X509KeyManager) KeyFactory(java.security.KeyFactory) KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509TrustManager(javax.net.ssl.X509TrustManager) BigInteger(java.math.BigInteger) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec)

Example 12 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project XobotOS by xamarin.

the class SSLParametersImpl method createDefaultKeyManager.

private static X509KeyManager createDefaultKeyManager() {
    try {
        String algorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(null, null);
        KeyManager[] kms = kmf.getKeyManagers();
        return findX509KeyManager(kms);
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (KeyStoreException e) {
        return null;
    } catch (UnrecoverableKeyException e) {
        return null;
    }
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 13 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project OpenAM by OpenRock.

the class AMX509KeyManagerImpl method initX509KeyManager.

// create sunX509KeyManager
//
// for example:
//     Create/load a keystore
//     Get instance of a "SunX509" KeyManagerFactory "kmf"
//     init the KeyManagerFactory with the keystore
public X509KeyManager initX509KeyManager(String ksType, String ksFile, String ksProvider, AMCallbackHandler cbHandle) {
    KeyManagerFactory kmf = null;
    // initialize KeyStore and get KeyManagerFactory 
    try {
        bundle = amCache.getResBundle(bundleName, Locale.getDefault());
        KeyStore.CallbackHandlerProtection callback = null;
        if (cbHandle != null) {
            callback = new KeyStore.CallbackHandlerProtection(cbHandle);
        } else {
            String passwdPrompt = bundle.getString("KeyStorePrompt");
            callback = new KeyStore.CallbackHandlerProtection(new AMCallbackHandler(passwdPrompt));
        }
        if (ksType.equalsIgnoreCase("JKS") || ksType.equalsIgnoreCase("PKCS12")) {
            builder = KeyStore.Builder.newInstance(ksType, Security.getProvider(ksProvider), new File(ksFile), callback);
        } else if (keyStoreType.equalsIgnoreCase("PKCS11")) {
            builder = KeyStore.Builder.newInstance(ksType, Security.getProvider(ksProvider), callback);
        }
        KeyStoreBuilderParameters param = new KeyStoreBuilderParameters(builder);
        kmf = KeyManagerFactory.getInstance(algorithm, provider);
        kmf.init(param);
    } catch (Exception e) {
        debug.error(e.toString());
    }
    return (X509KeyManager) kmf.getKeyManagers()[0];
}
Also used : KeyStoreBuilderParameters(javax.net.ssl.KeyStoreBuilderParameters) X509KeyManager(javax.net.ssl.X509KeyManager) KeyStore(java.security.KeyStore) File(java.io.File) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 14 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project tomcat by apache.

the class JSSEUtil method getKeyManagers.

@Override
public KeyManager[] getKeyManagers() throws Exception {
    String keystoreType = certificate.getCertificateKeystoreType();
    String keyAlias = certificate.getCertificateKeyAlias();
    String algorithm = sslHostConfig.getKeyManagerAlgorithm();
    String keyPass = certificate.getCertificateKeyPassword();
    // defaults vary between JSSE and OpenSSL.
    if (keyPass == null) {
        keyPass = certificate.getCertificateKeystorePassword();
    }
    KeyManager[] kms = null;
    KeyStore ks = certificate.getCertificateKeystore();
    if (ks == null) {
        // create an in-memory keystore and import the private key
        // and the certificate chain from the PEM files
        ks = KeyStore.getInstance("JKS");
        ks.load(null, null);
        PEMFile privateKeyFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile() != null ? certificate.getCertificateKeyFile() : certificate.getCertificateFile()), keyPass);
        PEMFile certificateFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()));
        Collection<Certificate> chain = new ArrayList<>();
        chain.addAll(certificateFile.getCertificates());
        if (certificate.getCertificateChainFile() != null) {
            PEMFile certificateChainFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()));
            chain.addAll(certificateChainFile.getCertificates());
        }
        if (keyAlias == null) {
            keyAlias = "tomcat";
        }
        ks.setKeyEntry(keyAlias, privateKeyFile.getPrivateKey(), keyPass.toCharArray(), chain.toArray(new Certificate[chain.size()]));
    }
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, keyPass.toCharArray());
    kms = kmf.getKeyManagers();
    if (kms == null) {
        return kms;
    }
    if (keyAlias != null) {
        String alias = keyAlias;
        // JKS keystores always convert the alias name to lower case
        if ("JKS".equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for (int i = 0; i < kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], alias);
        }
    }
    return kms;
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) SSLHostConfigCertificate(org.apache.tomcat.util.net.SSLHostConfigCertificate)

Example 15 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project cas by apereo.

the class FileTrustStoreSslSocketFactory method getTrustedSslContext.

/**
     * Gets the trusted ssl context.
     *
     * @param trustStoreFile     the trust store file
     * @param trustStorePassword the trust store password
     * @param trustStoreType     the trust store type
     * @return the trusted ssl context
     */
private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword, final String trustStoreType) {
    try {
        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();
        try (InputStream casStream = trustStoreFile.getInputStream()) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }
        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);
        final KeyManager[] keyManagers = { new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager)) };
        final TrustManager[] trustManagers = { new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager)) };
        final SSLContext context = SSLContexts.custom().useProtocol("SSL").build();
        context.init(keyManagers, trustManagers, null);
        return context;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
Also used : InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager)

Aggregations

X509KeyManager (javax.net.ssl.X509KeyManager)20 KeyManager (javax.net.ssl.KeyManager)9 IOException (java.io.IOException)8 X509Certificate (java.security.cert.X509Certificate)8 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)8 CertificateException (java.security.cert.CertificateException)7 X509ExtendedKeyManager (javax.net.ssl.X509ExtendedKeyManager)7 X509TrustManager (javax.net.ssl.X509TrustManager)7 KeyStore (java.security.KeyStore)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 KeyFactory (java.security.KeyFactory)4 KeyPair (java.security.KeyPair)4 KeyPairGenerator (java.security.KeyPairGenerator)4 PublicKey (java.security.PublicKey)4 DHPublicKey (javax.crypto.interfaces.DHPublicKey)4 DHParameterSpec (javax.crypto.spec.DHParameterSpec)4 DHPublicKeySpec (javax.crypto.spec.DHPublicKeySpec)4 SSLContext (javax.net.ssl.SSLContext)4 SSLException (javax.net.ssl.SSLException)4 PrivateKey (java.security.PrivateKey)3