Search in sources :

Example 31 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class TrustChainValidator_resolveIssuersTest method testResolveIssuers_noAIAExists_notAvailViaResolver_validateNotResolved.

public void testResolveIssuers_noAIAExists_notAvailViaResolver_validateNotResolved() throws Exception {
    final TrustChainValidatorWrapper validator = new TrustChainValidatorWrapper() {

        protected Collection<X509Certificate> downloadCertsFromAIA(String url) throws NHINDException {
            throw new NHINDException();
        }
    };
    validator.setCertificateResolver(new ArrayList<CertificateResolver>());
    final Collection<X509Certificate> resolvedIssuers = new ArrayList<X509Certificate>();
    final Collection<X509Certificate> anchors = new ArrayList<X509Certificate>();
    final TrustChainValidatorWrapper spyValidator = spy(validator);
    spyValidator.resolveIssuers(TestUtils.loadCertificate("altNameOnly.der"), resolvedIssuers, 0, anchors);
    assertEquals(0, resolvedIssuers.size());
    verify(spyValidator, times(0)).downloadCertsFromAIA((String) any());
}
Also used : TrustChainValidatorWrapper(org.nhindirect.stagent.trust.TrustChainValidator_getIntermediateCertsByAIATest.TrustChainValidatorWrapper) ArrayList(java.util.ArrayList) CertificateResolver(org.nhindirect.stagent.cert.CertificateResolver) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate)

Example 32 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class TrustChainValidator_getIntermediateCertsByAIATest method testGetIntermediateCertsByAIA_emptyAIA_validateNotResolved.

public void testGetIntermediateCertsByAIA_emptyAIA_validateNotResolved() throws Exception {
    final TrustChainValidatorWrapper validator = new TrustChainValidatorWrapper() {

        protected Collection<X509Certificate> downloadCertsFromAIA(String url) throws NHINDException {
            try {
                retrievedURL = url;
                return Arrays.asList(TestUtils.loadCertificate("bob.der"));
            } catch (Exception e) {
                throw new NHINDException(e);
            }
        }
    };
    final TrustChainValidatorWrapper spyValidator = spy(validator);
    Collection<X509Certificate> downloadedCerts = spyValidator.getIntermediateCertsByAIA(TestUtils.loadCertificate("altNameOnly.der"));
    assertNull(spyValidator.retrievedURL);
    assertEquals(0, downloadedCerts.size());
    verify(spyValidator, never()).downloadCertsFromAIA((String) any());
}
Also used : NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) NHINDException(org.nhindirect.stagent.NHINDException)

Example 33 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class TestUtils method certFromData.

public static X509Certificate certFromData(byte[] data) {
    X509Certificate retVal = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                } else
                    retVal = cert;
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
        bais.close();
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyStore(java.security.KeyStore) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 34 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class CertCommands method certFromData.

private X509Certificate certFromData(byte[] data) {
    X509Certificate retVal = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, "".toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, "".toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                } else
                    retVal = cert;
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (retVal == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
        }
        bais.close();
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyStore(java.security.KeyStore) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 35 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class DNSCertificateStore method lookupDNS.

protected Collection<X509Certificate> lookupDNS(String name) {
    String domain;
    String lookupName = name.replace('@', '.');
    Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    // get the domain of the address
    int index;
    if ((index = name.indexOf("@")) > -1)
        domain = name.substring(index + 1);
    else
        domain = name;
    try {
        // try the configured servers first
        Lookup lu = new Lookup(new Name(lookupName), Type.CERT);
        // default retries is 3, limite to 2
        lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout));
        lu.setSearchPath((String[]) null);
        Record[] retRecords = null;
        try {
            retRecords = lu.run();
        } catch (Exception e) {
            LOGGER.warn("Error using recusive DNS CERT lookup for name " + lookupName + "\r\nFalling back to looking up NS record for a targeted search", e);
        }
        if (retRecords == null || retRecords.length == 0) {
            Name tempDomain;
            // try to find the resource's name server records
            // the address may be an alias so check if there is a CNAME record
            lu = new Lookup(new Name(lookupName), Type.CNAME);
            lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout));
            lu.setSearchPath((String[]) null);
            retRecords = lu.run();
            if (retRecords != null && retRecords.length > 0) {
                CNAMERecord cnameRect = (CNAMERecord) retRecords[0];
                tempDomain = cnameRect.getTarget();
            } else
                // not a CNAME						
                tempDomain = new Name(domain);
            // look for a name server records
            while (tempDomain.labels() > 1) {
                lu = new Lookup(tempDomain, Type.NS);
                lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout));
                lu.setSearchPath((String[]) null);
                retRecords = lu.run();
                if (retRecords != null && retRecords.length > 0)
                    break;
                tempDomain = new Name(tempDomain.toString().substring((tempDomain.toString().indexOf(".") + 1)));
            }
            if (retRecords == null || retRecords.length == 0)
                // can't find a name server... bail
                return retVal;
            String[] remoteServers = new String[retRecords.length];
            for (int i = 0; i < remoteServers.length - 0; ++i) {
                remoteServers[i] = ((NSRecord) retRecords[i]).getTarget().toString();
            }
            // search the name servers for the cert
            lu = new Lookup(new Name(lookupName), Type.CERT);
            ExtendedResolver remoteResolver = createExResolver(remoteServers, 2, 3);
            if (remoteResolver.getResolvers().length > 0) {
                lu.setResolver(remoteResolver);
                lu.setSearchPath((String[]) null);
                // CLEAR THE CACHE!!!  We are seeing instances where an NXRRSET is cached because
                // a DNS provider is trying to handle a request that it should be delegating
                // The purpose of bypassing the DNS provider and going directly to the NS server
                // is to avoid issues like this
                /*
					 * Change of heart on clearing the DNS cache.  Covering up the NXRRSET hides potential issues
					 * with incorrect DNS configuration.  It is important that NXRRSET issues are discovered and corrected
					 * so all participants in the community participate in a consistent manner.
					 */
                //lu.setCache(new Cache(DClass.IN));
                retRecords = lu.run();
            } else {
                // null out NS records
                retRecords = null;
            }
        }
        if (retRecords != null) {
            retVal = new ArrayList<X509Certificate>();
            for (Record rec : retRecords) {
                if (rec instanceof CERTRecord) {
                    CERTRecord certRec = (CERTRecord) rec;
                    switch(certRec.getCertType()) {
                        case CERTRecord.PKIX:
                            {
                                Certificate certToAdd = convertPKIXRecordToCert(certRec);
                                if (// may not be an X509Cert
                                certToAdd != null && certToAdd instanceof X509Certificate)
                                    retVal.add((X509Certificate) certToAdd);
                                break;
                            }
                        case CERTRecord.URI:
                            {
                                Certificate certToAdd = convertIPKIXRecordToCert(certRec);
                                if (// may not be an X509Cert
                                certToAdd != null && certToAdd instanceof X509Certificate)
                                    retVal.add((X509Certificate) certToAdd);
                                break;
                            }
                        default:
                            {
                                LOGGER.warn("Unknown CERT type " + certRec.getCertType() + " encountered for lookup name" + lookupName);
                            }
                    }
                }
            }
        } else if (// if this is an email address, do the search again and the host level
        domain.length() < name.length())
            retVal = lookupDNS(domain);
    } catch (Exception e) {
        e.printStackTrace();
        throw new NHINDException("", e);
    }
    // add or update the local cert store
    if (retVal != null && retVal.size() > 0 && localStoreDelegate != null) {
        for (X509Certificate cert : retVal) {
            if (localStoreDelegate != null) {
                if (localStoreDelegate.contains(cert))
                    localStoreDelegate.update(cert);
                else
                    localStoreDelegate.add(cert);
            }
        }
        try {
            if (cache != null)
                cache.put(name, retVal);
        } catch (CacheException e) {
        /*
				 * TODO: handle exception
				 */
        }
    }
    return retVal;
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) CacheException(org.apache.jcs.access.exception.CacheException) ArrayList(java.util.ArrayList) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) CacheException(org.apache.jcs.access.exception.CacheException) NHINDException(org.nhindirect.stagent.NHINDException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) Name(org.xbill.DNS.Name) CNAMERecord(org.xbill.DNS.CNAMERecord) CERTRecord(org.xbill.DNS.CERTRecord) Lookup(org.xbill.DNS.Lookup) CNAMERecord(org.xbill.DNS.CNAMERecord) CERTRecord(org.xbill.DNS.CERTRecord) NSRecord(org.xbill.DNS.NSRecord) Record(org.xbill.DNS.Record) NSRecord(org.xbill.DNS.NSRecord) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

NHINDException (org.nhindirect.stagent.NHINDException)45 X509Certificate (java.security.cert.X509Certificate)30 ArrayList (java.util.ArrayList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 IOException (java.io.IOException)11 Key (java.security.Key)10 PrivateKey (java.security.PrivateKey)10 KeyStore (java.security.KeyStore)9 CacheException (org.apache.jcs.access.exception.CacheException)7 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)7 MessagingException (javax.mail.MessagingException)6 Collection (java.util.Collection)4 UnknownHostException (java.net.UnknownHostException)3 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)3 Certificate (java.security.cert.Certificate)3 InternetHeaders (javax.mail.internet.InternetHeaders)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)3 File (java.io.File)2