Search in sources :

Example 6 with CERTRecord

use of org.xbill.DNS.CERTRecord in project nhin-d by DirectProject.

the class DNSCertificateStore_convertIPKIXRecordToCertTest method testConvertIPKIXRecordToCert_invalidURL_assertNoCertificate.

public void testConvertIPKIXRecordToCert_invalidURL_assertNoCertificate() throws Exception {
    final CERTRecord rec = mock(CERTRecord.class);
    when(rec.getCert()).thenReturn("http://localhost:9481/bogus".getBytes());
    final DNSCertificateStore store = new DNSCertificateStore();
    Certificate cert = store.convertIPKIXRecordToCert(rec);
    assertNull(cert);
}
Also used : CERTRecord(org.xbill.DNS.CERTRecord) Certificate(java.security.cert.Certificate)

Example 7 with CERTRecord

use of org.xbill.DNS.CERTRecord in project nhin-d by DirectProject.

the class ConfigServiceDNSStore method processCERTRecordRequest.

/**
	 * Processes all DNS CERT requests.
	 * @param name The record name.  In many cases this a email address.
	 * @return Returns a set of record responses to the request.
	 * @throws DNSException
	 */
@SuppressWarnings("unused")
protected RRset processCERTRecordRequest(String name) throws DNSException {
    if (name.endsWith("."))
        name = name.substring(0, name.length() - 1);
    Certificate[] certs;
    // use the certificate configuration service
    try {
        certs = proxy.getCertificatesForOwner(name, null);
    } catch (Exception e) {
        throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "DNS service proxy call for certificates failed: " + e.getMessage(), e);
    }
    if (certs == null || certs.length == 0) {
        // unless the call above was for an org level cert, it will probably always fail because the
        // "name" parameter has had all instances of "@" replaced with ".".  The certificate service 
        // stores owners using "@".
        // This is horrible, but try hitting the cert service replacing each "." with "@" one by one.
        // Start at the beginning of the address because this is more than likely where the "@" character
        // will be.
        int previousIndex = 0;
        int replaceIndex = 0;
        while ((replaceIndex = name.indexOf(".", previousIndex)) > -1) {
            char[] chars = name.toCharArray();
            chars[replaceIndex] = '@';
            try {
                certs = proxy.getCertificatesForOwner(String.copyValueOf(chars), null);
            } catch (Exception e) {
                throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "DNS service proxy call for certificates failed: " + e.getMessage(), e);
            }
            if (certs != null && certs.length > 0)
                break;
            if (replaceIndex >= (name.length() - 1))
                break;
            previousIndex = replaceIndex + 1;
        }
    }
    if (certs == null || certs.length == 0)
        return null;
    if (!name.endsWith("."))
        name += ".";
    RRset retVal = new RRset();
    try {
        for (Certificate cert : certs) {
            int certRecordType = CERTRecord.PKIX;
            byte[] retData = null;
            X509Certificate xCert = null;
            try {
                // need to convert to cert container because this might be 
                // a certificate with wrapped private key data
                final CertUtils.CertContainer cont = CertUtils.toCertContainer(cert.getData());
                xCert = cont.getCert();
                // check if this is a compliant certificate with the configured policy... if not, move on
                if (!isCertCompliantWithPolicy(xCert))
                    continue;
                retData = xCert.getEncoded();
            } catch (CertificateConversionException e) {
            // probably not a Certificate... might be a URL
            }
            if (xCert == null) {
                // see if it's a URL
                try {
                    retData = cert.getData();
                    URL url = new URL(new String(retData));
                    certRecordType = CERTRecord.URI;
                } catch (Exception e) {
                    throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "Failure while parsing CERT record data: " + e.getMessage(), e);
                }
            }
            int keyTag = 0;
            int alg = 0;
            if (xCert != null && xCert.getPublicKey() instanceof RSAKey) {
                RSAKey key = (RSAKey) xCert.getPublicKey();
                byte[] modulus = key.getModulus().toByteArray();
                keyTag = (modulus[modulus.length - 2] << 8) & 0xFF00;
                keyTag |= modulus[modulus.length - 1] & 0xFF;
                alg = 5;
            }
            CERTRecord rec = new CERTRecord(Name.fromString(name), DClass.IN, 86400L, certRecordType, keyTag, alg, /*public key alg, RFC 4034*/
            retData);
            retVal.addRR(rec);
        }
    } catch (Exception e) {
        throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "Failure while parsing CERT record data: " + e.getMessage(), e);
    }
    // resulting in an empty RR set
    return (retVal.size() == 0) ? null : retVal;
}
Also used : RSAKey(java.security.interfaces.RSAKey) RRset(org.xbill.DNS.RRset) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) ConfigServiceURL(org.nhindirect.dns.annotation.ConfigServiceURL) CertUtils(org.nhindirect.config.model.utils.CertUtils) CERTRecord(org.xbill.DNS.CERTRecord) X509Certificate(java.security.cert.X509Certificate) Certificate(org.nhind.config.Certificate)

Example 8 with CERTRecord

use of org.xbill.DNS.CERTRecord in project nhin-d by DirectProject.

the class DNSRecordUtils method createX509CERTRecord.

/**
	 * Creates a DNS CERT record containing an X509 public certificate.
	 * @param address The name or address corresponding to the certificate.
	 * @param ttl The time to live in seconds.
	 * @param cert The X509 public certificate to be stored with the name/address. 
	 * @return A DNSRecord representing a CERT type record.
	 * @throws ConfigurationStoreException
	 */
public static DNSRecord createX509CERTRecord(String address, long ttl, X509Certificate cert) throws ConfigurationStoreException {
    if (!address.endsWith("."))
        address = address + ".";
    try {
        int keyTag = 0;
        if (cert.getPublicKey() instanceof RSAKey) {
            RSAKey key = (RSAKey) cert.getPublicKey();
            byte[] modulus = key.getModulus().toByteArray();
            keyTag = (modulus[modulus.length - 2] << 8) & 0xFF00;
            keyTag |= modulus[modulus.length - 1] & 0xFF;
        }
        CERTRecord rec = new CERTRecord(Name.fromString(address), DClass.IN, ttl, CERTRecord.PKIX, keyTag, 5, /*public key alg, RFC 4034*/
        cert.getEncoded());
        return DNSRecord.fromWire(rec.toWireCanonical());
    } catch (Exception e) {
        throw new ConfigurationStoreException("Failed to create DNS CERT record: " + e.getMessage(), e);
    }
}
Also used : RSAKey(java.security.interfaces.RSAKey) CERTRecord(org.xbill.DNS.CERTRecord) ConfigurationStoreException(org.nhindirect.config.store.ConfigurationStoreException) IOException(java.io.IOException) ConfigurationStoreException(org.nhindirect.config.store.ConfigurationStoreException)

Example 9 with CERTRecord

use of org.xbill.DNS.CERTRecord 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)

Example 10 with CERTRecord

use of org.xbill.DNS.CERTRecord in project nhin-d by DirectProject.

the class DNSCertificateStore_convertIPKIXRecordToCertTest method testConvertIPKIXRecordToCert_validCERTData_assertCertificate.

public void testConvertIPKIXRecordToCert_validCERTData_assertCertificate() throws Exception {
    File file = new File("./src/test/resources/certs/certCheckA.der");
    final String url = filePrefix + file.getAbsolutePath();
    final CERTRecord rec = mock(CERTRecord.class);
    when(rec.getCert()).thenReturn(url.getBytes());
    final DNSCertificateStore store = new DNSCertificateStore();
    Certificate cert = store.convertIPKIXRecordToCert(rec);
    assertNotNull(cert);
}
Also used : CERTRecord(org.xbill.DNS.CERTRecord) File(java.io.File) Certificate(java.security.cert.Certificate)

Aggregations

CERTRecord (org.xbill.DNS.CERTRecord)12 IOException (java.io.IOException)5 Certificate (java.security.cert.Certificate)4 X509Certificate (java.security.cert.X509Certificate)4 RSAKey (java.security.interfaces.RSAKey)4 ArrayList (java.util.ArrayList)3 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)3 CNAMERecord (org.xbill.DNS.CNAMERecord)3 NSRecord (org.xbill.DNS.NSRecord)3 File (java.io.File)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 CertificateEncodingException (javax.security.cert.CertificateEncodingException)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Answer (org.mockito.stubbing.Answer)2 Certificate (org.nhindirect.config.model.Certificate)2 DNSRecord (org.nhindirect.config.model.DNSRecord)2 DNSEntryForm (org.nhindirect.config.ui.form.DNSEntryForm)2 AAAARecord (org.xbill.DNS.AAAARecord)2 ARecord (org.xbill.DNS.ARecord)2 MXRecord (org.xbill.DNS.MXRecord)2