Search in sources :

Example 71 with X509Certificate

use of java.security.cert.X509Certificate in project Openfire by igniterealtime.

the class CertificateManager method installReply.

/**
     * Installs the Certificate Authority reply returned as part of the signing request. The certificate
     * being signed will get its certificate chain updated with the imported certificate(s). An exception
     * will be thrown if the replied certificate does not match a local certificate or if the signing
     * authority is not known by the server (i.e. keystore and truststore files)
     *
     * The identity of the entity that has signed the reply is verified against the provided trust store.
     *
     * The
     *
     * @param keyStore    key store where the certificate is stored.
     * @param trustStore  key store where ca certificates are stored.
     * @param keyPassword password of the keystore.
     * @param alias the alias of the existing certificate being signed.
     * @param inputStream the stream containing the CA reply.
     * @return true if the CA reply was successfully processed.
     * @throws Exception
     */
public static boolean installReply(KeyStore keyStore, KeyStore trustStore, char[] keyPassword, String alias, InputStream inputStream) throws Exception {
    // Check that there is a certificate for the specified alias
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
    if (certificate == null) {
        Log.warn("Certificate not found for alias: " + alias);
        return false;
    }
    // Retrieve the private key of the stored certificate
    PrivateKey privKey = (PrivateKey) keyStore.getKey(alias, keyPassword);
    // Load certificates found in the PEM input stream
    Collection<X509Certificate> certs = parseCertificates(inputStream);
    if (certs.isEmpty()) {
        throw new Exception("Reply has no certificates");
    }
    List<X509Certificate> newCerts;
    if (certs.size() == 1) {
        // Reply has only one certificate
        newCerts = establishCertChain(keyStore, trustStore, null, certs.iterator().next());
    } else {
        // Reply has a chain of certificates
        newCerts = validateReply(keyStore, trustStore, alias, null, certs);
    }
    if (newCerts == null) {
        return false;
    }
    keyStore.setKeyEntry(alias, privKey, keyPassword, newCerts.toArray(new X509Certificate[newCerts.size()]));
    // Notify listeners that a new certificate has been created
    for (CertificateEventListener listener : listeners) {
        try {
            listener.certificateSigned(keyStore, alias, newCerts);
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
    return true;
}
Also used : PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 72 with X509Certificate

use of java.security.cert.X509Certificate in project Openfire by igniterealtime.

the class CertificateManager method getEndEntityCertificate.

/**
     * Decide whether or not to trust the given supplied certificate chain, returning the
     * End Entity Certificate in this case where it can, and null otherwise.
     * A self-signed certificate will, for example, return null.
     * For certain failures, we SHOULD generate an exception - revocations and the like,
     * but we currently do not.
     *
     * @param chain an array of X509Certificate where the first one is the endEntityCertificate.
     * @param certStore a keystore containing untrusted certificates (including ICAs, etc).
     * @param trustStore a keystore containing Trust Anchors (most-trusted CA certificates).
     * @return trusted end-entity certificate, or null.
     */
public static X509Certificate getEndEntityCertificate(Certificate[] chain, KeyStore certStore, KeyStore trustStore) {
    if (chain.length == 0) {
        return null;
    }
    X509Certificate first = (X509Certificate) chain[0];
    try {
        first.checkValidity();
    } catch (CertificateException e) {
        Log.warn("EE Certificate not valid: " + e.getMessage());
        return null;
    }
    if (chain.length == 1 && first.getSubjectX500Principal().equals(first.getIssuerX500Principal())) {
        // Chain is single cert, and self-signed.
        try {
            if (trustStore.getCertificateAlias(first) != null) {
                // Interesting case: trusted self-signed cert.
                return first;
            }
        } catch (KeyStoreException e) {
            Log.warn("Keystore error while looking for self-signed cert; assuming untrusted.");
        }
        return null;
    }
    final List<Certificate> all_certs = new ArrayList<>();
    try {
        // It's a mystery why these objects are different.
        for (Enumeration<String> aliases = certStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (certStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) certStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Now add the trusted certs.
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (trustStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Finally, add all the certs in the chain:
        for (int i = 0; i < chain.length; ++i) {
            all_certs.add(chain[i]);
        }
        CertStore cs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(all_certs));
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(first);
        // / selector.setSubject(first.getSubjectX500Principal());
        PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, selector);
        params.addCertStore(cs);
        params.setDate(new Date());
        params.setRevocationEnabled(false);
        /* Code here is the right way to do things. */
        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType());
        CertPath cp = pathBuilder.build(params).getCertPath();
        /**
             * This section is an alternative to using CertPathBuilder which is
             * not as complete (or safe), but will emit much better errors. If
             * things break, swap around the code.
             *
             **** COMMENTED OUT. ****
            ArrayList<X509Certificate> ls = new ArrayList<X509Certificate>();
            for (int i = 0; i < chain.length; ++i) {
                ls.add((X509Certificate) chain[i]);
            }
            for (X509Certificate last = ls.get(ls.size() - 1); !last
                    .getIssuerX500Principal().equals(last.getSubjectX500Principal()); last = ls
                    .get(ls.size() - 1)) {
                X509CertSelector sel = new X509CertSelector();
                sel.setSubject(last.getIssuerX500Principal());
                ls.add((X509Certificate) cs.getCertificates(sel).toArray()[0]);
            }
            CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(ls);
             ****** END ALTERNATIVE. ****
             */
        // Not entirely sure if I need to do this with CertPathBuilder.
        // Can't hurt.
        CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
        pathValidator.validate(cp, params);
        return (X509Certificate) cp.getCertificates().get(0);
    } catch (CertPathBuilderException e) {
        Log.warn("Path builder: " + e.getMessage());
    } catch (CertPathValidatorException e) {
        Log.warn("Path validator: " + e.getMessage());
    } catch (Exception e) {
        Log.warn("Unkown exception while validating certificate chain: " + e.getMessage());
    }
    return null;
}
Also used : PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509CertSelector(java.security.cert.X509CertSelector) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 73 with X509Certificate

use of java.security.cert.X509Certificate in project Openfire by igniterealtime.

the class CertificateManager method buildChain.

/**
     * Builds the certificate chain of the specified certificate based on the known list of certificates
     * that were issued by their respective Principals. Returns true if the entire chain of all certificates
     * was successfully built.
     *
     * @param certificate certificate to build its chain.
     * @param answer      the certificate chain for the corresponding certificate.
     * @param knownCerts  list of known certificates grouped by their issues (i.e. Principals).
     * @return true if the entire chain of all certificates was successfully built.
     */
private static boolean buildChain(X509Certificate certificate, LinkedList<X509Certificate> answer, Map<String, List<X509Certificate>> knownCerts) {
    Principal subject = certificate.getSubjectDN();
    Principal issuer = certificate.getIssuerDN();
    // is present in the subject)
    if (subject.equals(issuer)) {
        answer.addFirst(certificate);
        return true;
    }
    // Get the list of known certificates of the certificate's issuer
    List<X509Certificate> issuerCerts = knownCerts.get(issuer.getName());
    if (issuerCerts == null || issuerCerts.isEmpty()) {
        // No certificates were found so building of chain failed
        return false;
    }
    for (X509Certificate issuerCert : issuerCerts) {
        PublicKey publickey = issuerCert.getPublicKey();
        try {
            // Verify the certificate with the specified public key
            certificate.verify(publickey);
            // Certificate was verified successfully so build chain of issuer's certificate
            if (!buildChain(issuerCert, answer, knownCerts)) {
                return false;
            }
        } catch (Exception exception) {
            // Failed to verify certificate
            return false;
        }
    }
    answer.addFirst(certificate);
    return true;
}
Also used : PublicKey(java.security.PublicKey) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 74 with X509Certificate

use of java.security.cert.X509Certificate in project Openfire by igniterealtime.

the class HttpBindServlet method createNewSession.

protected void createNewSession(AsyncContext context, Element rootNode) throws IOException {
    final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);
    try {
        final X509Certificate[] certificates = (X509Certificate[]) context.getRequest().getAttribute("javax.servlet.request.X509Certificate");
        final HttpConnection connection = new HttpConnection(rid, context.getRequest().isSecure(), certificates, context);
        final InetAddress address = InetAddress.getByName(context.getRequest().getRemoteAddr());
        connection.setSession(sessionManager.createSession(address, rootNode, connection));
        if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
            Log.info(new Date() + ": HTTP RECV(" + connection.getSession().getStreamID().getID() + "): " + rootNode.asXML());
        }
    } catch (UnauthorizedException | HttpBindException e) {
        // Server wasn't initialized yet.
        sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization.");
    }
}
Also used : UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) InetAddress(java.net.InetAddress) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date)

Example 75 with X509Certificate

use of java.security.cert.X509Certificate in project Openfire by igniterealtime.

the class IdentityStore method generateCSR.

/**
     * Creates a Certificate Signing Request based on the private key and certificate identified by the provided alias.
     *
     * When the alias does not identify a private key and/or certificate, this method will throw an exception.
     *
     * The certificate that is identified by the provided alias can be an unsigned certificate, but also a certificate
     * that is already signed. The latter implies that the generated request is a request for certificate renewal.
     *
     * An invocation of this method does not change the state of the underlying store.
     *
     * @param alias An identifier for a private key / certificate in this store (cannot be null).
     * @return A PEM-encoded Certificate Signing Request (never null).
     */
public String generateCSR(String alias) throws CertificateStoreConfigException {
    // Input validation
    if (alias == null || alias.trim().isEmpty()) {
        throw new IllegalArgumentException("Argument 'alias' cannot be null or an empty String.");
    }
    alias = alias.trim();
    try {
        if (!store.containsAlias(alias)) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': the alias does not exist in the store.");
        }
        final Certificate certificate = store.getCertificate(alias);
        if (certificate == null || (!(certificate instanceof X509Certificate))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding certificate in the store, or it is not an X509 certificate.");
        }
        final Key key = store.getKey(alias, configuration.getPassword());
        if (key == null || (!(key instanceof PrivateKey))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding key in the store, or it is not a private key.");
        }
        final String pemCSR = CertificateManager.createSigningRequest((X509Certificate) certificate, (PrivateKey) key);
        return pemCSR;
    } catch (IOException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "'", e);
    }
}
Also used : IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

X509Certificate (java.security.cert.X509Certificate)1706 IOException (java.io.IOException)336 CertificateException (java.security.cert.CertificateException)272 ByteArrayInputStream (java.io.ByteArrayInputStream)260 CertificateFactory (java.security.cert.CertificateFactory)251 ArrayList (java.util.ArrayList)232 Certificate (java.security.cert.Certificate)227 KeyStore (java.security.KeyStore)177 PrivateKey (java.security.PrivateKey)150 InputStream (java.io.InputStream)134 File (java.io.File)112 KeyStoreException (java.security.KeyStoreException)112 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 GeneralSecurityException (java.security.GeneralSecurityException)100 Test (org.junit.Test)90 List (java.util.List)89 PublicKey (java.security.PublicKey)88 X509TrustManager (javax.net.ssl.X509TrustManager)80 X500Principal (javax.security.auth.x500.X500Principal)76 HashSet (java.util.HashSet)64