Search in sources :

Example 6 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException 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 7 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertUtils method certAndWrappedKeyToRawByteFormat.

public static byte[] certAndWrappedKeyToRawByteFormat(byte[] wrappedKey, X509Certificate cert) throws CertificateConversionException {
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    try {
        // write the magic string
        outStream.write(KEY_PAIR_START_STRING);
        // write the size of the the wrapped key
        // size is going to be > 256, so need to split it into two bytes
        int size = wrappedKey.length;
        outStream.write((byte) ((size >> 8) & 0xFF));
        outStream.write((byte) (size & 0xFF));
        // write the wrapped key data
        outStream.write(wrappedKey);
        // write the encoded certificate
        outStream.write(cert.getEncoded());
        return outStream.toByteArray();
    } catch (Exception e) {
        throw new CertificateConversionException("Failed to convert wrapped key and cert to byte stream.", e);
    } finally {
        IOUtils.closeQuietly(outStream);
    }
}
Also used : CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException)

Example 8 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertUtils method toCertContainer.

/**
     * Creates a certificate container that consists of the X509 certificate and its private key (if it exists).
     * @param data A DER encoded representation of either an X509 certificate, an unencrypted PKCS12 container, or
     * a combination of an X509Certificate and wrapped private key.
     * @return A container object with the X509 certificate and private key (it it exists).
     * @throws CertificateConversionException
     */
public static CertContainer toCertContainer(byte[] data, char[] keyStorePassPhrase, char[] privateKeyPassPhrase) throws CertificateConversionException {
    CertContainer certContainer = null;
    try {
        ByteArrayInputStream inputStream = null;
        // first check if the byte array starts with the magic string
        if (isByteDataWrappedKeyPair(data)) {
            int idx = KEY_PAIR_START_STRING.length;
            // the next 2 bytes are the size of the certificate data
            // convert it to an int
            // need to take into consideration that bytes in Java are signed and be aware of compliment representations
            int high = (data[idx] >= 0) ? data[idx] : (data[idx] + 256);
            ++idx;
            int low = (data[idx] >= 0) ? data[idx] : (data[idx] + 256);
            int wrappedDatasize = low | (high << 8);
            ++idx;
            final byte[] wrappedData = Arrays.copyOfRange(data, idx, idx + wrappedDatasize);
            idx += wrappedDatasize;
            final ByteArrayInputStream bais = new ByteArrayInputStream(Arrays.copyOfRange(data, idx, data.length));
            try {
                return new CertContainer((X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais), wrappedData);
            } finally {
                IOUtils.closeQuietly(bais);
                IOUtils.closeQuietly(inputStream);
            }
        }
        // magic string doesn't exist.. let's try some other methods
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", getJCEProviderName());
            localKeyStore.load(bais, keyStorePassPhrase);
            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, privateKeyPassPhrase);
                if (key != null && key instanceof PrivateKey) {
                    certContainer = new CertContainer(cert, key);
                }
            }
        } catch (Exception e) {
        // must not be a PKCS12 stream, go on to next step
        }
        if (certContainer == null) {
            //try X509 certificate factory next       
            bais.reset();
            bais = new ByteArrayInputStream(data);
            X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
            certContainer = new CertContainer(cert, (Key) null);
        }
        bais.close();
    } catch (Exception e) {
        throw new CertificateConversionException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return certContainer;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException)

Example 9 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class CertUtils method changePkcs12Protection.

/**
     * Modifies the keystore and private key protection on a PKCS12 keystore. 
     * @param bytes The PKCS12 encoded as byte array that will be modified.
     * @param oldKeyStorePassPhrase The current pass phrase protecting the keystore file.
     * @param oldPrivateKeyPassPhrase The current pass phrase protecting the private key.
     * @param newKeystorePassPhrase The new pass phrase protecting the keystore file.
     * @param newPrivateKeyPassPhrase The new pass phrase protecting the private key.
     * @return The modified PKCS12 key store encoded as a byte array/ 
     */
public static byte[] changePkcs12Protection(byte[] bytes, char[] oldKeyStorePassPhrase, char[] oldPrivateKeyPassPhrase, char[] newKeystorePassPhrase, char[] newPrivateKeyPassPhrase) {
    if (bytes == null || bytes.length == 0)
        throw new IllegalArgumentException("Pkcs byte stream cannot be null or empty.");
    byte[] retVal = null;
    final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
    // lets try this a as a PKCS12 data stream first
    try {
        final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", getJCEProviderName());
        localKeyStore.load(bais, oldKeyStorePassPhrase);
        final Enumeration<String> aliases = localKeyStore.aliases();
        // we are really expecting only one alias 
        if (aliases.hasMoreElements()) {
            final String alias = aliases.nextElement();
            X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
            // check if there is private key
            final Key key = localKeyStore.getKey(alias, oldPrivateKeyPassPhrase);
            if (key != null && key instanceof PrivateKey) {
                // now convert to a pcks12 format without the new passphrase
                localKeyStore.setKeyEntry("privCert", key, newPrivateKeyPassPhrase, new java.security.cert.Certificate[] { cert });
                localKeyStore.store(outStr, newKeystorePassPhrase);
                retVal = outStr.toByteArray();
            }
        }
    } catch (Exception e) {
        throw new CertificateConversionException("Failed to strip encryption for PKCS stream.", e);
    } finally {
        try {
            bais.close();
        } catch (Exception e) {
        /* no-op */
        }
        try {
            outStr.close();
        } catch (Exception e) {
        /* no-op */
        }
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 10 with CertificateConversionException

use of org.nhindirect.config.model.exceptions.CertificateConversionException in project nhin-d by DirectProject.

the class EntityModelConversion method toEntityTrustBundle.

public static org.nhindirect.config.store.TrustBundle toEntityTrustBundle(TrustBundle bundle) {
    if (bundle == null)
        return null;
    final org.nhindirect.config.store.TrustBundle retVal = new org.nhindirect.config.store.TrustBundle();
    final Collection<org.nhindirect.config.store.TrustBundleAnchor> trustAnchors = new ArrayList<org.nhindirect.config.store.TrustBundleAnchor>();
    if (bundle.getTrustBundleAnchors() != null) {
        for (TrustBundleAnchor anchor : bundle.getTrustBundleAnchors()) {
            final org.nhindirect.config.store.TrustBundleAnchor retAnchor = new org.nhindirect.config.store.TrustBundleAnchor();
            try {
                retAnchor.setData(anchor.getAnchorData());
            } catch (CertificateException e) {
                throw new CertificateConversionException(e);
            }
            // the entity object sets all other attributes based on the cert data,
            // no need to explicitly set it here
            retAnchor.setTrustBundle(retVal);
            trustAnchors.add(retAnchor);
        }
    }
    retVal.setBundleName(bundle.getBundleName());
    retVal.setBundleURL(bundle.getBundleURL());
    if (bundle.getCheckSum() == null)
        retVal.setCheckSum("");
    else
        retVal.setCheckSum(bundle.getCheckSum());
    retVal.setCreateTime(bundle.getCreateTime());
    retVal.setId(bundle.getId());
    retVal.setLastRefreshAttempt(bundle.getLastRefreshAttempt());
    if (bundle.getLastRefreshError() != null)
        retVal.setLastRefreshError(org.nhindirect.config.store.BundleRefreshError.valueOf(bundle.getLastRefreshError().toString()));
    retVal.setLastSuccessfulRefresh(bundle.getLastSuccessfulRefresh());
    retVal.setRefreshInterval(bundle.getRefreshInterval());
    if (bundle.getSigningCertificateData() != null) {
        try {
            retVal.setSigningCertificateData(bundle.getSigningCertificateData());
        } catch (CertificateException e) {
            throw new CertificateConversionException(e);
        }
    }
    retVal.setTrustBundleAnchors(trustAnchors);
    return retVal;
}
Also used : ArrayList(java.util.ArrayList) TrustBundle(org.nhindirect.config.model.TrustBundle) CertificateException(org.nhindirect.config.store.CertificateException) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) TrustBundleAnchor(org.nhindirect.config.model.TrustBundleAnchor)

Aggregations

CertificateConversionException (org.nhindirect.config.model.exceptions.CertificateConversionException)10 X509Certificate (java.security.cert.X509Certificate)6 IOException (java.io.IOException)4 CertificateParsingException (java.security.cert.CertificateParsingException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Key (java.security.Key)3 KeyStore (java.security.KeyStore)3 PrivateKey (java.security.PrivateKey)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 URL (java.net.URL)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 RSAKey (java.security.interfaces.RSAKey)1 ArrayList (java.util.ArrayList)1 EntityManager (javax.persistence.EntityManager)1 Test (org.junit.Test)1 InvocationOnMock (org.mockito.invocation.InvocationOnMock)1 Certificate (org.nhind.config.Certificate)1 BootstrappedKeyStoreProtectionManager (org.nhindirect.common.crypto.impl.BootstrappedKeyStoreProtectionManager)1