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;
}
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;
}
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);
}
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;
}
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;
}
Aggregations