Search in sources :

Example 76 with X509Certificate

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

the class IdentityStore method corresponds.

protected boolean corresponds(String alias, List<X509Certificate> certificates) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    if (!store.containsAlias(alias)) {
        return false;
    }
    final Key key = store.getKey(alias, configuration.getPassword());
    if (key == null) {
        return false;
    }
    if (!(key instanceof PrivateKey)) {
        return false;
    }
    final Certificate certificate = store.getCertificate(alias);
    if (certificate == null) {
        return false;
    }
    if (!(certificate instanceof X509Certificate)) {
        return false;
    }
    final X509Certificate x509Certificate = (X509Certificate) certificate;
    // First certificate in the chain should correspond with the certificate in the store
    if (!x509Certificate.getPublicKey().equals(certificates.get(0).getPublicKey())) {
        return false;
    }
    return true;
}
Also used : X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 77 with X509Certificate

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

the class ExternalClientSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    if (isComplete()) {
        throw new IllegalStateException("Authentication exchange already completed.");
    }
    // There will be no further steps. Either authentication succeeds or fails, but in any case, we're done.
    complete = true;
    final Connection connection = session.getConnection();
    Certificate[] peerCertificates = connection.getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length < 1) {
        throw new SaslException("No peer certificates.");
    }
    final KeyStore keyStore = connection.getConfiguration().getIdentityStore().getStore();
    final KeyStore trustStore = connection.getConfiguration().getTrustStore().getStore();
    final X509Certificate trusted = CertificateManager.getEndEntityCertificate(peerCertificates, keyStore, trustStore);
    if (trusted == null) {
        throw new SaslException("Certificate chain of peer is not trusted.");
    }
    // Process client identities / principals.
    final ArrayList<String> principals = new ArrayList<>();
    principals.addAll(CertificateManager.getClientIdentities(trusted));
    String principal;
    switch(principals.size()) {
        case 0:
            principal = "";
            break;
        default:
            Log.debug("More than one principal found, using the first one.");
        // intended fall-through;
        case 1:
            principal = principals.get(0);
            break;
    }
    // Process requested user name.
    String username;
    if (response != null && response.length > 0) {
        username = new String(response, StandardCharsets.UTF_8);
    } else {
        username = null;
    }
    if (username == null || username.length() == 0) {
        // cause an authorization failure.
        for (String princ : principals) {
            final String mappedUsername = AuthorizationManager.map(princ);
            if (!mappedUsername.equals(princ)) {
                username = mappedUsername;
                principal = princ;
                break;
            }
        }
        if (username == null || username.length() == 0) {
            // Still no username.  Punt.
            username = principal;
        }
        Log.debug("No username requested, using: {}", username);
    }
    // Its possible that either/both username and principal are null here. The providers should not allow a null authorization
    if (AuthorizationManager.authorize(username, principal)) {
        Log.debug("Principal {} authorized to username {}", principal, username);
        authorizationID = username;
        // Success!
        return null;
    }
    throw new SaslException();
}
Also used : Connection(org.jivesoftware.openfire.Connection) ArrayList(java.util.ArrayList) SaslException(javax.security.sasl.SaslException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 78 with X509Certificate

use of java.security.cert.X509Certificate in project languagetool by languagetool-org.

the class HTTPTools method disableCertChecks.

/**
   * For testing, we disable all checks because we use a self-signed certificate on the server
   * side and we want this test to run everywhere without importing the certificate into the JVM's trust store.
   *
   * See http://stackoverflow.com/questions/2893819/telling-java-to-accept-self-signed-ssl-certificate
   */
static void disableCertChecks() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 79 with X509Certificate

use of java.security.cert.X509Certificate in project c-geo by just-radovan.

the class cgBase method trustAllHosts.

public static void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.trustAllHosts: " + e.toString());
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 80 with X509Certificate

use of java.security.cert.X509Certificate in project hudson-2.x by hudson.

the class UpdateSite method verifySignature.

/**
     * Verifies the signature in the update center data file.
     */
private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject signature = o.getJSONObject("signature");
    if (signature.isNullObject()) {
        LOGGER.severe("No signature block found");
        return false;
    }
    o.remove("signature");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    {
        // load and verify certificates
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        for (Object cert : o.getJSONArray("certificates")) {
            X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
            c.checkValidity();
            certs.add(c);
        }
        // all default root CAs in JVM are trusted, plus certs bundled in Hudson
        Set<TrustAnchor> anchors = CertificateUtil.getDefaultRootCAs();
        ServletContext context = Hudson.getInstance().servletContext;
        for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
            // skip text files that are meant to be documentation
            if (cert.endsWith(".txt"))
                continue;
            anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(context.getResourceAsStream(cert)), null));
        }
        CertificateUtil.validatePath(certs);
    }
    // this is for computing a digest to check sanity
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);
    // this is for computing a signature
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(certs.get(0));
    SignatureOutputStream sos = new SignatureOutputStream(sig);
    JSONCanonicalUtils.write(o, new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8"));
    // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
    // (which is more likely than someone tampering with update center), we can tell
    String computedDigest = new String(Base64.encode(sha1.digest()));
    String providedDigest = signature.getString("digest");
    if (!computedDigest.equalsIgnoreCase(providedDigest)) {
        LOGGER.severe("Digest mismatch: " + computedDigest + " vs " + providedDigest);
        return false;
    }
    if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) {
        LOGGER.severe("Signature in the update center doesn't match with the certificate");
        return false;
    }
    return true;
}
Also used : TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) Set(java.util.Set) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) JSONObject(net.sf.json.JSONObject) SignatureOutputStream(org.jvnet.hudson.crypto.SignatureOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestOutputStream(java.security.DigestOutputStream) Signature(java.security.Signature) ServletContext(javax.servlet.ServletContext) JSONObject(net.sf.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter) MessageDigest(java.security.MessageDigest) NullOutputStream(org.apache.commons.io.output.NullOutputStream)

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