use of org.mozilla.jss.netscape.security.x509.X500Name in project ca3sCore by kuehne-trustable-de.
the class CaCmpConnector method buildCertRequest.
/**
* @param certReqId
* @param csr
* @param hmacSecret
* @return PKIMessage
* @throws GeneralSecurityException
*/
public PKIMessage buildCertRequest(long certReqId, final CSR csr, final String hmacSecret) throws GeneralSecurityException {
// read the pem csr and verify the signature
PKCS10CertificationRequest p10Req;
try {
p10Req = cryptoUtil.parseCertificateRequest(csr.getCsrBase64()).getP10Req();
} catch (IOException e) {
LOGGER.error("parsing csr", e);
throw new GeneralSecurityException(e.getMessage());
}
List<RDN> rdnList = new ArrayList<>();
for (de.trustable.ca3s.core.domain.RDN rdnDao : csr.getRdns()) {
LOGGER.debug("rdnDao : " + rdnDao.getRdnAttributes());
List<AttributeTypeAndValue> attrTVList = new ArrayList<AttributeTypeAndValue>();
if (rdnDao != null && rdnDao.getRdnAttributes() != null) {
for (RDNAttribute rdnAttr : rdnDao.getRdnAttributes()) {
ASN1ObjectIdentifier aoi = new ASN1ObjectIdentifier(rdnAttr.getAttributeType());
ASN1Encodable ae = new DERUTF8String(rdnAttr.getAttributeValue());
AttributeTypeAndValue attrTV = new AttributeTypeAndValue(aoi, ae);
attrTVList.add(attrTV);
}
}
RDN rdn = new RDN(attrTVList.toArray(new AttributeTypeAndValue[attrTVList.size()]));
LOGGER.debug("rdn : " + rdn.size() + " elements");
rdnList.add(rdn);
}
X500Name subjectDN = new X500Name(rdnList.toArray(new RDN[rdnList.size()]));
LOGGER.debug("subjectDN : " + subjectDN);
Collection<Extension> certExtList = new ArrayList<>();
// copy CSR attributes to Extension list
for (Attribute attribute : p10Req.getAttributes()) {
for (ASN1Encodable asn1Encodable : attribute.getAttributeValues()) {
if (asn1Encodable != null) {
try {
Extensions extensions = Extensions.getInstance(asn1Encodable);
for (ASN1ObjectIdentifier oid : extensions.getExtensionOIDs()) {
LOGGER.debug("copying oid '" + oid.toString() + "' from csr to PKIMessage");
certExtList.add(extensions.getExtension(oid));
}
} catch (IllegalArgumentException iae) {
LOGGER.debug("processing asn1 value '" + asn1Encodable + "' caused exception", iae);
}
}
}
}
final SubjectPublicKeyInfo keyInfo = p10Req.getSubjectPublicKeyInfo();
return cryptoUtil.buildCertRequest(certReqId, subjectDN, certExtList, keyInfo, hmacSecret);
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project ca3sCore by kuehne-trustable-de.
the class CaCmpConnector method revokeCertificate.
/**
* @param certDao
* @param crlReason
* @param revocationDate
* @param caConnConfig
* @throws GeneralSecurityException
*/
public void revokeCertificate(Certificate certDao, final CRLReason crlReason, final Date revocationDate, CAConnectorConfig caConnConfig) throws GeneralSecurityException {
String plainSecret = protUtil.unprotectString(caConnConfig.getSecret().getContentBase64());
revokeCertificate(new X500Name(certDao.getIssuer()), new X500Name(certDao.getSubject()), new BigInteger(certDao.getSerial()), crlReason, plainSecret, caConnConfig.getCaUrl(), caConnConfig.getSelector());
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project ca3sCore by kuehne-trustable-de.
the class Ca3sFallbackBundleFactory method newKeyBundle.
@Override
public KeyCertBundle newKeyBundle(final String bundleName, long minValiditySeconds) throws GeneralSecurityException {
KeyPair localKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
try {
InetAddress ip = InetAddress.getLocalHost();
String hostname = ip.getHostName();
LOG.debug("requesting certificate for host : " + hostname);
String x500Name = "CN=" + hostname;
if (!dnSuffix.trim().isEmpty()) {
x500Name += ", " + dnSuffix;
}
X500Name subject = new X500Name(x500Name);
GeneralName[] sanArray = new GeneralName[1];
sanArray[0] = new GeneralName(GeneralName.dNSName, hostname);
GeneralNames gns = new GeneralNames(sanArray);
List<Map<String, Object>> extensions = new ArrayList<>();
Map<String, Object> serverAuthMap = new HashMap<>();
serverAuthMap.put("oid", Extension.extendedKeyUsage.getId());
serverAuthMap.put("critical", Boolean.FALSE);
List<String> valList = new ArrayList<>();
valList.add(KeyPurposeId.id_kp_serverAuth.getId());
serverAuthMap.put("value", valList);
extensions.add(serverAuthMap);
LOG.debug("building certificate for SAN '{}' and EKU {}", hostname, Extension.extendedKeyUsage.getId());
X509Certificate issuedCertificate = cryptoUtil.issueCertificate(x500Issuer, getRootKeyPair(), subject, SubjectPublicKeyInfo.getInstance(localKeyPair.getPublic().getEncoded()), Calendar.HOUR, 1, gns, extensions, PKILevel.END_ENTITY);
// build the (short) chain
X509Certificate[] certificateChain = { issuedCertificate, getRootCertificate() };
LOG.debug("returning temp. certificate : " + issuedCertificate);
return new KeyCertBundle(bundleName, certificateChain, issuedCertificate, localKeyPair.getPrivate());
} catch (IOException e) {
// certificate creation failed with an exception not inheriting from 'GeneralSecurityException'
throw new GeneralSecurityException(e);
}
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project ca3sCore by kuehne-trustable-de.
the class CertificateUtil method createCertificate.
/**
* @param pemCert
* @param csr
* @param executionId
* @param x509Cert
* @param tbsDigestBase64
* @return
* @throws CertificateEncodingException
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws CertificateParsingException
* @throws CertificateException
* @throws InvalidKeyException
* @throws NoSuchProviderException
* @throws SignatureException
*/
private Certificate createCertificate(final String pemCert, final CSR csr, final String executionId, X509Certificate x509Cert, String tbsDigestBase64) throws CertificateEncodingException, IOException, NoSuchAlgorithmException, CertificateParsingException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException {
Certificate cert;
LOG.debug("creating new certificate '" + x509Cert.getSubjectX500Principal().getName() + "'");
byte[] certBytes = x509Cert.getEncoded();
X509CertificateHolder x509CertHolder = new X509CertificateHolder(certBytes);
cert = new Certificate();
cert.setCertificateAttributes(new HashSet<>());
String type = "X509V" + x509Cert.getVersion();
cert.setType(type);
String serial = x509Cert.getSerialNumber().toString();
cert.setSerial(serial);
cert.setContent(pemCert);
if (csr != null) {
// do not overwrite an existing CSR
cert.setCsr(csr);
}
// indexed key for searching
cert.setTbsDigest(tbsDigestBase64);
// derive a readable description
String desc = cryptoUtil.getDescription(x509Cert);
cert.setDescription(CryptoService.limitLength(desc, 250));
// good old SHA1 fingerprint
String fingerprint = Base64.encodeBase64String(generateSHA1Fingerprint(certBytes));
cert.setFingerprint(fingerprint);
cert.setValidFrom(DateUtil.asInstant(x509Cert.getNotBefore()));
cert.setValidTo(DateUtil.asInstant(x509Cert.getNotAfter()));
cert.setActive(true);
Date now = new Date();
if (x509Cert.getNotBefore().after(now)) {
cert.setActive(false);
}
if (x509Cert.getNotAfter().before(now)) {
cert.setActive(false);
}
// initialize revocation details
cert.setRevokedSince(null);
cert.setRevocationReason(null);
cert.setRevoked(false);
if (executionId != null) {
cert.setCreationExecutionId(executionId);
}
cert.setContentAddedAt(Instant.now());
String issuer = CryptoService.limitLength(x509Cert.getIssuerX500Principal().getName(), 250);
cert.setIssuer(issuer);
String subject = CryptoService.limitLength(x509Cert.getSubjectX500Principal().getName(), 250);
cert.setSubject(subject);
cert.setSelfsigned(false);
certificateRepository.save(cert);
interpretBasicConstraint(x509Cert, cert);
// add the basic key usages a attributes
usageAsCertAttributes(x509Cert.getKeyUsage(), cert);
// add the extended key usages a attributes
List<String> extKeyUsageList = x509Cert.getExtendedKeyUsage();
if (extKeyUsageList != null) {
for (String extUsage : extKeyUsageList) {
setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_EXTENDED_USAGE_OID, extUsage);
setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_EXTENDED_USAGE, OidNameMapper.lookupOid(extUsage));
}
}
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ISSUER, issuer.toLowerCase());
X500Name x500NameIssuer = x509CertHolder.getIssuer();
insertNameAttributes(cert, CertificateAttribute.ATTRIBUTE_ISSUER, x500NameIssuer);
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SUBJECT, subject.toLowerCase());
X500Name x500NameSubject = x509CertHolder.getSubject();
insertNameAttributes(cert, CertificateAttribute.ATTRIBUTE_SUBJECT, x500NameSubject);
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_TYPE, type);
JcaX509ExtensionUtils util = new JcaX509ExtensionUtils();
// build two SKI variants for cert identification
SubjectKeyIdentifier ski = util.createSubjectKeyIdentifier(x509Cert.getPublicKey());
String b46Ski = Base64.encodeBase64String(ski.getKeyIdentifier());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SKI, b46Ski);
SubjectKeyIdentifier skiTruncated = util.createTruncatedSubjectKeyIdentifier(x509Cert.getPublicKey());
if (!ski.equals(skiTruncated)) {
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SKI, Base64.encodeBase64String(skiTruncated.getKeyIdentifier()));
}
// add two serial variants
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SERIAL, serial);
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SERIAL_PADDED, getPaddedSerial(serial));
// add validity period
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALID_FROM_TIMESTAMP, "" + x509Cert.getNotBefore().getTime());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALID_TO_TIMESTAMP, "" + x509Cert.getNotAfter().getTime());
long validityPeriod = (x509Cert.getNotAfter().getTime() - x509Cert.getNotBefore().getTime()) / 1000L;
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALIDITY_PERIOD, "" + validityPeriod);
addAdditionalCertificateAttributes(x509Cert, cert);
copyCsrAttributesToCertificate(csr, cert);
certificateRepository.save(cert);
certificateAttributeRepository.saveAll(cert.getCertificateAttributes());
if (x500NameIssuer.equals(x500NameSubject)) {
// check whether is really selfsigned
x509Cert.verify(x509Cert.getPublicKey());
// don't insert the self-reference. This leads to no good when JSON-serializing the object
// The selfsigned-attribute will mark the fact!
// cert.setIssuingCertificate(cert);
// mark it as self signed
cert.setSelfsigned(true);
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SELFSIGNED, "true");
// don't build a self reference here
cert.setIssuingCertificate(null);
cert.setRootCertificate(null);
cert.setRoot(cert.getSubject());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ROOT, cert.getSubject().toLowerCase());
LOG.debug("certificate '" + x509Cert.getSubjectX500Principal().getName() + "' is selfsigned");
} else {
// try to build cert chain
try {
Certificate issuingCert = findIssuingCertificate(x509CertHolder);
if (issuingCert == null) {
LOG.info("unable to find issuer for non-self-signed certificate '" + x509Cert.getSubjectX500Principal().getName() + "' right now ...");
} else {
cert.setIssuingCertificate(issuingCert);
if (LOG.isDebugEnabled()) {
LOG.debug("certificate '" + x509Cert.getSubjectX500Principal().getName() + "' issued by " + issuingCert.getSubject());
}
}
Certificate rootCert = findRootCertificate(issuingCert);
if (rootCert != null) {
cert.setRootCertificate(rootCert);
cert.setRoot(rootCert.getSubject());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ROOT, rootCert.getSubject().toLowerCase());
}
} catch (GeneralSecurityException gse) {
// LOG.debug("exception while retrieving issuer", gse);
LOG.info("problem retrieving issuer for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' right now ...");
}
}
certificateRepository.save(cert);
// LOG.debug("certificate id '" + cert.getId() +"' post-save");
certificateAttributeRepository.saveAll(cert.getCertificateAttributes());
LOG.debug("certificate id '{}' saved containing #{} attributes", cert.getId(), cert.getCertificateAttributes().size());
for (CertificateAttribute cad : cert.getCertificateAttributes()) {
LOG.debug("Name '" + cad.getName() + "' got value '" + cad.getValue() + "'");
}
final X509Principal principal = PrincipalUtil.getSubjectX509Principal(x509Cert);
final Vector<?> values = principal.getValues(X509Name.CN);
String cn = values.size() > 0 ? (String) values.get(0) : null;
List<String> sanList = getCertAttributes(cert, CertificateAttribute.ATTRIBUTE_SAN);
sanList.addAll(getCertAttributes(cert, CsrAttribute.ATTRIBUTE_TYPED_SAN));
sanList.addAll(getCertAttributes(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN));
List<Certificate> replacedCerts = findReplaceCandidates(Instant.now(), cn, sanList);
if (replacedCerts.isEmpty()) {
LOG.debug("certificate id {} does not replace any certificate", cert.getId());
} else {
for (Certificate replacedCert : replacedCerts) {
if (!cert.equals(replacedCert)) {
LOG.debug("certificate id {} replaces certificate id {}", cert.getId(), replacedCert.getId());
setCertMultiValueAttribute(replacedCert, CertificateAttribute.ATTRIBUTE_REPLACED_BY, cert.getId().toString());
certificateAttributeRepository.saveAll(replacedCert.getCertificateAttributes());
}
}
}
return cert;
}
use of org.mozilla.jss.netscape.security.x509.X500Name in project ca3sCore by kuehne-trustable-de.
the class CertificateUtil method addAdditionalCertificateAttributes.
/**
* @param x509Cert
* @param cert
* @throws CertificateParsingException
* @throws IOException
*/
public void addAdditionalCertificateAttributes(X509Certificate x509Cert, Certificate cert) throws CertificateParsingException, IOException {
int version = Integer.parseInt(getCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ATTRIBUTES_VERSION, "0"));
if (version == 0) {
// extract signature algo
String keyAlgName = x509Cert.getPublicKey().getAlgorithm();
cert.setKeyAlgorithm(keyAlgName.toLowerCase());
AlgorithmInfo algorithmInfo = new AlgorithmInfo(x509Cert.getSigAlgName());
cert.setHashingAlgorithm(algorithmInfo.getHashAlgName());
cert.setPaddingAlgorithm(algorithmInfo.getPaddingAlgName());
cert.setSigningAlgorithm(algorithmInfo.getSigAlgName());
try {
String curveName = deriveCurveName(x509Cert.getPublicKey());
LOG.info("found curve name " + curveName + " for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' with key algo " + keyAlgName);
cert.setCurveName(curveName.toLowerCase());
} catch (GeneralSecurityException e) {
if (keyAlgName.contains("ec")) {
LOG.info("unable to derive curve name for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' with key algo " + keyAlgName);
}
}
String subject = x509Cert.getSubjectX500Principal().getName();
if (subject != null && subject.trim().length() > 0) {
try {
InetAddressValidator inv = InetAddressValidator.getInstance();
List<Rdn> rdnList = new LdapName(subject).getRdns();
for (Rdn rdn : rdnList) {
if ("CN".equalsIgnoreCase(rdn.getType())) {
String cn = rdn.getValue().toString();
if (inv.isValid(cn)) {
LOG.debug("CN found IP in subject: '{}'", cn);
setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN, "IP:" + cn);
} else {
LOG.debug("CN found DNS name in subject: '{}'", cn);
setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN, "DNS:" + cn);
}
}
}
} catch (InvalidNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String allSans = "";
// list all SANs
if (x509Cert.getSubjectAlternativeNames() != null) {
Collection<List<?>> altNames = x509Cert.getSubjectAlternativeNames();
if (altNames != null) {
for (List<?> altName : altNames) {
int altNameType = (Integer) altName.get(0);
String sanValue = "";
if (altName.get(1) instanceof String) {
sanValue = ((String) altName.get(1)).toLowerCase();
} else if (GeneralName.otherName == altNameType) {
// sanValue = "--other value--";
} else if (altName.get(1) instanceof byte[]) {
sanValue = new String((byte[]) (altName.get(1))).toLowerCase();
} else {
LOG.info("unexpected content type in SANS : {}", altName.get(1).toString());
}
if (allSans.length() > 0) {
allSans += ";";
}
allSans += sanValue;
setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_SAN, sanValue);
setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_SAN, getTypedSAN(altNameType, sanValue));
}
}
}
cert.setSans(CryptoUtil.limitLength(allSans, 250));
int keyLength = getAlignedKeyLength(x509Cert.getPublicKey());
cert.setKeyLength(keyLength);
List<String> crlUrls = getCrlDistributionPoints(x509Cert);
for (String crlUrl : crlUrls) {
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_CRL_URL, crlUrl);
}
String ocspUrl = getOCSPUrl(x509Cert);
if (ocspUrl != null) {
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_OCSP_URL, ocspUrl);
}
List<String> certificatePolicyIds = getCertificatePolicies(x509Cert);
for (String polId : certificatePolicyIds) {
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_POLICY_ID, polId);
}
}
if (version < 2) {
try {
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_FINGERPRINT_SHA1, DigestUtils.sha1Hex(x509Cert.getEncoded()).toLowerCase());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_FINGERPRINT_SHA256, DigestUtils.sha3_256Hex(x509Cert.getEncoded()).toLowerCase());
} catch (CertificateEncodingException e) {
LOG.error("Problem getting encoded certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", e);
}
try {
if (!cert.getSubject().trim().isEmpty()) {
X500Name x500Name = new X500Name(cert.getSubject());
for (RDN rdn : x500Name.getRDNs()) {
AttributeTypeAndValue[] attrTVArr = rdn.getTypesAndValues();
for (AttributeTypeAndValue attrTV : attrTVArr) {
String rdnReadableName = OidNameMapper.lookupOid(attrTV.getType().toString());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_RDN_PREFIX + rdnReadableName.toUpperCase(), attrTV.getValue().toString());
}
}
}
} catch (IllegalArgumentException iae) {
LOG.error("Problem building X500Name for subject for certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", iae);
}
}
if (version < CURRENT_ATTRIBUTES_VERSION) {
try {
String subjectRfc2253 = getNormalizedName(cert.getSubject());
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SUBJECT_RFC_2253, subjectRfc2253, false);
} catch (InvalidNameException e) {
LOG.error("Problem building RFC 2253-styled subject for certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", e);
}
setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ATTRIBUTES_VERSION, "" + CURRENT_ATTRIBUTES_VERSION, false);
}
}
Aggregations