Search in sources :

Example 81 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.

the class ZTSClient method getAWSLambdaServiceCertificate.

/**
 * For AWS Lambda functions generate a new private key, request a
 * x.509 certificate based on the requested CSR and return both to
 * the client in order to establish tls connections with other
 * Athenz enabled services.
 * @param domainName name of the domain
 * @param serviceName name of the service
 * @param account AWS account name that the function runs in
 * @param provider name of the provider service for AWS Lambda
 * @return AWSLambdaIdentity with private key and certificate
 */
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account, String provider) {
    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Domain and Service must be specified");
    }
    if (account == null || provider == null) {
        throw new IllegalArgumentException("AWS Account and Provider must be specified");
    }
    if (x509CsrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // first we're going to generate a private key for the request
    AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
    try {
        lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    // we need to generate an csr with an instance register object
    InstanceRegisterInformation info = new InstanceRegisterInformation();
    info.setDomain(domainName.toLowerCase());
    info.setService(serviceName.toLowerCase());
    info.setProvider(provider.toLowerCase());
    final String athenzService = info.getDomain() + "." + info.getService();
    // generate our dn which will be based on our service name
    StringBuilder dnBuilder = new StringBuilder(128);
    dnBuilder.append("cn=");
    dnBuilder.append(athenzService);
    if (x509CsrDn != null) {
        dnBuilder.append(',');
        dnBuilder.append(x509CsrDn);
    }
    // now let's generate our dsnName field based on our principal's details
    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(info.getService());
    hostBuilder.append('.');
    hostBuilder.append(info.getDomain().replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(x509CsrDomain);
    StringBuilder instanceHostBuilder = new StringBuilder(128);
    instanceHostBuilder.append("lambda-");
    instanceHostBuilder.append(account);
    instanceHostBuilder.append('-');
    instanceHostBuilder.append(info.getService());
    instanceHostBuilder.append(".instanceid.athenz.");
    instanceHostBuilder.append(x509CsrDomain);
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString()));
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString()));
    try {
        info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    // finally obtain attestation data for lambda
    info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));
    // request the x.509 certificate from zts server
    Map<String, List<String>> responseHeaders = new HashMap<>();
    InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);
    try {
        lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    return lambdaIdentity;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DERIA5String(org.bouncycastle.asn1.DERIA5String) IOException(java.io.IOException) DERIA5String(org.bouncycastle.asn1.DERIA5String) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CryptoException(com.yahoo.athenz.auth.util.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 82 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.

the class Utils method createKeyStore.

/**
 * @param athensPublicKey the location on the public key file
 * @param athensPrivateKey the location of the private key file
 * @return a KeyStore with loaded key and certificate
 * @throws Exception KeyStore generation can throw Exception for many reasons
 */
public static KeyStore createKeyStore(final String athensPublicKey, final String athensPrivateKey) throws Exception {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
    X509Certificate certificate;
    PrivateKey privateKey = null;
    final InputStream publicCertStream;
    final InputStream privateKeyStream;
    try {
        if (Paths.get(athensPublicKey).isAbsolute() && Paths.get(athensPrivateKey).isAbsolute()) {
            // Can not cover this branch in unit test. Can not refer any files by absolute paths
            File certFile = new File(athensPublicKey);
            File keyFile = new File(athensPrivateKey);
            while (!certFile.exists() || !keyFile.exists()) {
                LOG.error("Missing Athenz public or private key files");
                Thread.sleep(1000);
            }
            publicCertStream = new FileInputStream(athensPublicKey);
            privateKeyStream = new FileInputStream(athensPrivateKey);
        } else {
            publicCertStream = Resources.getResource(athensPublicKey).openStream();
            privateKeyStream = Resources.getResource(athensPrivateKey).openStream();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    try (PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
        Object key = pemParser.readObject();
        if (key instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo();
            privateKey = pemConverter.getPrivateKey(pKeyInfo);
        } else if (key instanceof PrivateKeyInfo) {
            privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key);
        } else {
            throw new IllegalStateException("Unknown object type: " + key.getClass().getName());
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse private key", e);
    }
    certificate = (X509Certificate) cf.generateCertificate(publicCertStream);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    String alias = certificate.getSubjectX500Principal().getName();
    keyStore.load(null);
    keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] { certificate });
    return keyStore;
}
Also used : PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) PEMParser(org.bouncycastle.openssl.PEMParser) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) File(java.io.File) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 83 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.

the class SelfCertSignerFactory method create.

@Override
public CertSigner create() {
    // extract the private key for this self cert signer
    final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
    final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
    final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN, "cn=Self Signed Athenz CA,o=Athenz,c=US");
    if (pKeyFileName == null) {
        LOGGER.error("No private key path available for Self Cert Signer Factory");
        return null;
    }
    File caKey = new File(pKeyFileName);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
    // now generate a CSR for our own CA and self sign it
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
    } catch (OperatorCreationException | IOException ex) {
        LOGGER.error("Unable to generate X509 CSR for dn: " + csrDn + ", error: " + ex.getMessage());
        return null;
    }
    // generate our self signed certificate
    X500Principal subject = new X500Principal(csrDn);
    X500Name issuer = X500Name.getInstance(subject.getEncoded());
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    X509Certificate caCertificate = Crypto.generateX509Certificate(certReq, caPrivateKey, issuer, 30 * 24 * 60, true);
    return new SelfCertSigner(caPrivateKey, caCertificate);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrivateKey(java.security.PrivateKey) X500Principal(javax.security.auth.x500.X500Principal) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate)

Example 84 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.

the class Crypto method extractX509CertIPAddresses.

public static List<String> extractX509CertIPAddresses(X509Certificate x509Cert) {
    Collection<List<?>> altNames = null;
    try {
        altNames = x509Cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException ex) {
        LOG.error("extractX509IPAddresses: Caught CertificateParsingException when parsing certificate: " + ex.getMessage());
    }
    if (altNames == null) {
        return Collections.emptyList();
    }
    List<String> ipAddresses = new ArrayList<>();
    for (@SuppressWarnings("rawtypes") List item : altNames) {
        Integer type = (Integer) item.get(0);
        if (type == GeneralName.iPAddress) {
            ipAddresses.add((String) item.get(1));
        }
    }
    return ipAddresses;
}
Also used : BigInteger(java.math.BigInteger) CertificateParsingException(java.security.cert.CertificateParsingException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String)

Example 85 with Certificate

use of org.bouncycastle.asn1.x509.Certificate in project athenz by yahoo.

the class Crypto method extractX509CertDnsNames.

public static List<String> extractX509CertDnsNames(X509Certificate x509Cert) {
    Collection<List<?>> altNames = null;
    try {
        altNames = x509Cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException ex) {
        LOG.error("extractX509IPAddresses: Caught CertificateParsingException when parsing certificate: " + ex.getMessage());
    }
    if (altNames == null) {
        return Collections.emptyList();
    }
    List<String> dnsNames = new ArrayList<>();
    for (@SuppressWarnings("rawtypes") List item : altNames) {
        Integer type = (Integer) item.get(0);
        if (type == GeneralName.dNSName) {
            dnsNames.add((String) item.get(1));
        }
    }
    return dnsNames;
}
Also used : BigInteger(java.math.BigInteger) CertificateParsingException(java.security.cert.CertificateParsingException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String)

Aggregations

X509Certificate (java.security.cert.X509Certificate)95 IOException (java.io.IOException)82 ArrayList (java.util.ArrayList)46 X500Name (org.bouncycastle.asn1.x500.X500Name)43 Date (java.util.Date)33 List (java.util.List)33 CertificateParsingException (java.security.cert.CertificateParsingException)30 GeneralName (org.bouncycastle.asn1.x509.GeneralName)29 BigInteger (java.math.BigInteger)28 CertificateException (java.security.cert.CertificateException)27 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)26 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)25 CertificateEncodingException (java.security.cert.CertificateEncodingException)24 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)24 GeneralSecurityException (java.security.GeneralSecurityException)23 PrivateKey (java.security.PrivateKey)23 Enumeration (java.util.Enumeration)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 ContentSigner (org.bouncycastle.operator.ContentSigner)23 Certificate (java.security.cert.Certificate)22