Search in sources :

Example 76 with GeneralName

use of sun.security.x509.GeneralName in project athenz by yahoo.

the class ZTSClient method generateRoleCertificateRequest.

/**
 * Generate a Role Certificate request that could be sent to ZTS
 * to obtain a X509 Certificate for the requested role.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param roleDomainName name of the domain where role is defined
 * @param roleName name of the role to get a certificate request for
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return RoleCertificateRequest object
 */
public static RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain, final String principalService, final String roleDomainName, final String roleName, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    if (roleDomainName == null || roleName == null) {
        throw new IllegalArgumentException("Role DomainName and Name must be specified");
    }
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be our role resource value
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    String dn = "cn=" + roleDomainName.toLowerCase() + ":role." + roleName.toLowerCase();
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    // now let's generate our dsnName and email fields which will based on
    // our principal's details
    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(service);
    hostBuilder.append('.');
    hostBuilder.append(domain.replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(csrDomain);
    String hostName = hostBuilder.toString();
    String email = domain + "." + service + "@" + csrDomain;
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email));
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    RoleCertificateRequest req = new RoleCertificateRequest().setCsr(csr).setExpiryTime(Long.valueOf(expiryTime));
    return req;
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 77 with GeneralName

use of sun.security.x509.GeneralName in project athenz by yahoo.

the class ZTSClient method generateInstanceRefreshRequest.

/**
 * Generate a Instance Refresh request that could be sent to ZTS to
 * request a TLS certificate for a service.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return InstanceRefreshRequest object
 */
public static InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain, final String principalService, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    final String cn = domain + "." + service;
    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    // now let's generate our dsnName field based on our principal's details
    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(service);
    hostBuilder.append('.');
    hostBuilder.append(domain.replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(csrDomain);
    String hostName = hostBuilder.toString();
    GeneralName[] sanArray = new GeneralName[1];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    InstanceRefreshRequest req = new InstanceRefreshRequest().setCsr(csr).setExpiryTime(Integer.valueOf(expiryTime));
    return req;
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 78 with GeneralName

use of sun.security.x509.GeneralName in project athenz by yahoo.

the class Crypto method generateX509Certificate.

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {
    // set validity for the given number of minutes from now
    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();
    // Generate self-signed certificate
    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey).addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)).addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // see if we have the dns/rfc822/ip address extensions specified in the csr
        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch(names[i].getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                            altNames.add(names[i]);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }
        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER).build(caPrivateKey);
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));
    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error("generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }
    return cert;
}
Also used : Attribute(org.bouncycastle.asn1.pkcs.Attribute) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Extensions(org.bouncycastle.asn1.x509.Extensions) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ECPoint(org.bouncycastle.math.ec.ECPoint) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) FileNotFoundException(java.io.FileNotFoundException) CertificateParsingException(java.security.cert.CertificateParsingException) PEMException(org.bouncycastle.openssl.PEMException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 79 with GeneralName

use of sun.security.x509.GeneralName in project athenz by yahoo.

the class Crypto method extractX509CSRIPAddresses.

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {
    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException e) {
                    }
                }
            }
        }
    }
    return ipAddresses;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) UnknownHostException(java.net.UnknownHostException) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions) InetAddress(java.net.InetAddress)

Example 80 with GeneralName

use of sun.security.x509.GeneralName in project athenz by yahoo.

the class CryptoTest method testX509CSRrequestWithPrivateKeyOnly.

@Test(dataProvider = "x500Principal")
public void testX509CSRrequestWithPrivateKeyOnly(String x500Principal, boolean badRequest) throws Exception {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[] { otherName1, otherName2 };
    try {
        certRequest = Crypto.generateX509CSR(privateKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        // Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}
Also used : PrivateKey(java.security.PrivateKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CryptoException(com.yahoo.athenz.auth.util.CryptoException) Test(org.testng.annotations.Test)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)50 IOException (java.io.IOException)34 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)28 ArrayList (java.util.ArrayList)27 List (java.util.List)19 DERIA5String (org.bouncycastle.asn1.DERIA5String)19 GeneralName (org.apache.harmony.security.x509.GeneralName)18 X509Certificate (java.security.cert.X509Certificate)17 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)16 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)15 Date (java.util.Date)12 X500Name (org.bouncycastle.asn1.x500.X500Name)10 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)10 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)10 GeneralName (sun.security.x509.GeneralName)10 GeneralSecurityException (java.security.GeneralSecurityException)9 CertPathValidatorException (java.security.cert.CertPathValidatorException)9 Enumeration (java.util.Enumeration)9 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)9 CertificateExpiredException (java.security.cert.CertificateExpiredException)8