use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project jruby-openssl by jruby.
the class X509AuxCertificate method computeExFlags.
// NOTE: not all EXFLAGS are implemented!
private int computeExFlags() throws IOException {
int flags = 0;
/* V1 should mean no extensions ... */
if (getVersion() == 1) {
flags |= X509Utils.EXFLAG_V1;
}
if (getExtensionValue("2.5.29.19") != null) {
// BASIC_CONSTRAINTS
if (getBasicConstraints() != -1) {
// is CA
flags |= X509Utils.EXFLAG_CA;
}
flags |= X509Utils.EXFLAG_BCONS;
}
if (getSubjectX500Principal().equals(getIssuerX500Principal())) {
flags |= X509Utils.EXFLAG_SI;
// TODO duplicate code from X509Utils.checkIfIssuedBy
if (getExtensionValue("2.5.29.35") != null) {
// authorityKeyID
Object key = X509Utils.get(getExtensionValue("2.5.29.35"));
if (!(key instanceof ASN1Sequence))
key = X509Utils.get((DEROctetString) key);
final ASN1Sequence seq = (ASN1Sequence) key;
final AuthorityKeyIdentifier akid;
if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
akid = AuthorityKeyIdentifier.getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
} else {
akid = AuthorityKeyIdentifier.getInstance(seq);
}
if (akid.getKeyIdentifier() != null) {
if (getExtensionValue("2.5.29.14") != null) {
DEROctetString der = (DEROctetString) X509Utils.get(getExtensionValue("2.5.29.14"));
SubjectKeyIdentifier skid = SubjectKeyIdentifier.getInstance(X509Utils.get(der.getOctets()));
if (skid.getKeyIdentifier() != null) {
if (Arrays.equals(akid.getKeyIdentifier(), skid.getKeyIdentifier())) {
/* .. and the signature alg matches the PUBKEY alg: */
if (getSigAlgName().equals(getPublicKey().getAlgorithm())) {
flags |= X509Utils.EXFLAG_SS;
/* indicate self-signed */
}
}
}
}
}
}
}
if (getKeyUsage() != null) {
flags |= X509Utils.EXFLAG_XKUSAGE;
}
if (getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
flags |= X509Utils.EXFLAG_PROXY;
}
return flags;
}
use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project ddf by codice.
the class SamlAssertionValidatorImpl method validateHolderOfKeyConfirmation.
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
List<String> confirmationMethods = assertion.getConfirmationMethods();
boolean hasHokMethod = false;
for (String method : confirmationMethods) {
if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
hasHokMethod = true;
}
}
if (hasHokMethod) {
if (x509Certs != null && x509Certs.length > 0) {
List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
Node keyInfo = dom.getFirstChild();
Node x509Data = keyInfo.getFirstChild();
Node dataNode = x509Data.getFirstChild();
Node dataText = dataNode.getFirstChild();
X509Certificate tlsCertificate = x509Certs[0];
if (dataNode.getLocalName().equals("X509Certificate")) {
String textContent = dataText.getTextContent();
byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
// check that the certificate is still valid
cert.checkValidity();
// if the certs aren't the same, verify
if (!tlsCertificate.equals(cert)) {
// verify that the cert was signed by the same private key as the TLS cert
cert.verify(tlsCertificate.getPublicKey());
}
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
}
} else if (dataNode.getLocalName().equals("X509SubjectName")) {
String textContent = dataText.getTextContent();
// the assertion.
if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
}
} else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
// we have no way to support this confirmation type so we have to throw an error
throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
} else if (dataNode.getLocalName().equals("X509SKI")) {
String textContent = dataText.getTextContent();
byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
if (tlsSKI != null && tlsSKI.length > 0) {
ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
// assertion.
if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
} else {
throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
}
}
}
}
} else {
throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
}
}
}
use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project zaproxy by zaproxy.
the class SslCertificateServiceImpl method createCertForHost.
@Override
public KeyStore createCertForHost(CertData certData) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
}
CertData.Name[] certDataNames = certData.getSubjectAlternativeNames();
GeneralName[] subjectAlternativeNames = new GeneralName[certDataNames.length];
for (int i = 0; i < certDataNames.length; i++) {
CertData.Name certDataName = certDataNames[i];
subjectAlternativeNames[i] = new GeneralName(certDataName.getType(), certDataName.getValue());
}
if (certData.getCommonName() == null && subjectAlternativeNames.length == 0) {
throw new IllegalArgumentException("commonName is null and no subjectAlternativeNames are specified");
}
final KeyPair mykp = this.createKeyPair();
final PrivateKey privKey = mykp.getPrivate();
final PublicKey pubKey = mykp.getPublic();
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
if (certData.getCommonName() != null) {
namebld.addRDN(BCStyle.CN, certData.getCommonName());
}
namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
namebld.addRDN(BCStyle.O, "OWASP");
namebld.addRDN(BCStyle.C, "xx");
namebld.addRDN(BCStyle.EmailAddress, "zaproxy-develop@googlegroups.com");
long currentTime = System.currentTimeMillis();
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(currentTime - Duration.ofDays(SITE_CERTIFICATE_START_ADJUSTMENT).toMillis()), new Date(currentTime + Duration.ofDays(SITE_CERTIFICATE_END_VALIDITY_PERIOD).toMillis()), namebld.build(), pubKey);
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth }));
if (subjectAlternativeNames.length > 0) {
certGen.addExtension(Extension.subjectAlternativeName, certData.isSubjectAlternativeNameIsCritical(), new GeneralNames(subjectAlternativeNames));
}
ContentSigner sigGen;
try {
sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
} catch (OperatorCreationException e) {
throw new CertificateException(e);
}
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caPubKey);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate[] chain = new Certificate[2];
chain[1] = this.caCert;
chain[0] = cert;
ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
return ks;
}
use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project zaproxy by zaproxy.
the class SslCertificateUtils method createRootCA.
/**
* Creates a new Root CA certificate and returns private and public key as {@link KeyStore}. The
* {@link KeyStore#getDefaultType()} is used.
*
* @return
* @throws NoSuchAlgorithmException If no providers are found for 'RSA' key pair generator or
* 'SHA1PRNG' Secure random number generator
* @throws IllegalStateException in case of errors during assembling {@link KeyStore}
*/
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
final Date startDate = Calendar.getInstance().getTime();
final Date expireDate = new Date(startDate.getTime() + DEFAULT_VALIDITY_IN_MS);
final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
final KeyPair keypair = g.genKeyPair();
final PrivateKey privKey = keypair.getPrivate();
final PublicKey pubKey = keypair.getPublic();
Security.addProvider(new BouncyCastleProvider());
Random rnd = new Random();
// using the hash code of the user's name and home path, keeps anonymity
// but also gives user a chance to distinguish between each other
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
namebld.addRDN(BCStyle.O, "OWASP Root CA");
namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
namebld.addRDN(BCStyle.C, "xx");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
KeyStore ks = null;
try {
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setKeyEntry(org.parosproxy.paros.security.SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, org.parosproxy.paros.security.SslCertificateService.PASSPHRASE, new Certificate[] { cert });
} catch (final Exception e) {
throw new IllegalStateException("Errors during assembling root CA.", e);
}
return ks;
}
use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project keycloak by keycloak.
the class OCSPUtils method verifyResponse.
private static void verifyResponse(BasicOCSPResp basicOcspResponse, X509Certificate issuerCertificate, X509Certificate responderCertificate, byte[] requestNonce, Date date) throws NoSuchProviderException, NoSuchAlgorithmException, CertificateNotYetValidException, CertificateExpiredException, CertPathValidatorException {
List<X509CertificateHolder> certs = new ArrayList<>(Arrays.asList(basicOcspResponse.getCerts()));
X509Certificate signingCert = null;
try {
certs.add(new JcaX509CertificateHolder(issuerCertificate));
if (responderCertificate != null) {
certs.add(new JcaX509CertificateHolder(responderCertificate));
}
} catch (CertificateEncodingException e) {
e.printStackTrace();
}
if (certs.size() > 0) {
X500Name responderName = basicOcspResponse.getResponderId().toASN1Primitive().getName();
byte[] responderKey = basicOcspResponse.getResponderId().toASN1Primitive().getKeyHash();
if (responderName != null) {
logger.log(Level.INFO, "Responder Name: {0}", responderName.toString());
for (X509CertificateHolder certHolder : certs) {
try {
X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
X500Name respName = new X500Name(tempCert.getSubjectX500Principal().getName());
if (responderName.equals(respName)) {
signingCert = tempCert;
logger.log(Level.INFO, "Found a certificate whose principal \"{0}\" matches the responder name \"{1}\"", new Object[] { tempCert.getSubjectDN().getName(), responderName.toString() });
break;
}
} catch (CertificateException e) {
logger.log(Level.FINE, e.getMessage());
}
}
} else if (responderKey != null) {
SubjectKeyIdentifier responderSubjectKey = new SubjectKeyIdentifier(responderKey);
logger.log(Level.INFO, "Responder Key: {0}", Arrays.toString(responderKey));
for (X509CertificateHolder certHolder : certs) {
try {
X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
SubjectKeyIdentifier subjectKeyIdentifier = null;
if (certHolder.getExtensions() != null) {
subjectKeyIdentifier = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions());
}
if (subjectKeyIdentifier != null) {
logger.log(Level.INFO, "Certificate: {0}\nSubject Key Id: {1}", new Object[] { tempCert.getSubjectDN().getName(), Arrays.toString(subjectKeyIdentifier.getKeyIdentifier()) });
}
if (subjectKeyIdentifier != null && responderSubjectKey.equals(subjectKeyIdentifier)) {
signingCert = tempCert;
logger.log(Level.INFO, "Found a signer certificate \"{0}\" with the subject key extension value matching the responder key", signingCert.getSubjectDN().getName());
break;
}
subjectKeyIdentifier = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(tempCert.getPublicKey());
if (responderSubjectKey.equals(subjectKeyIdentifier)) {
signingCert = tempCert;
logger.log(Level.INFO, "Found a certificate \"{0}\" with the subject key matching the OCSP responder key", signingCert.getSubjectDN().getName());
break;
}
} catch (CertificateException e) {
logger.log(Level.FINE, e.getMessage());
}
}
}
}
if (signingCert != null) {
if (signingCert.equals(issuerCertificate)) {
logger.log(Level.INFO, "OCSP response is signed by the target''s Issuing CA");
} else if (responderCertificate != null && signingCert.equals(responderCertificate)) {
// https://www.ietf.org/rfc/rfc2560.txt
// 2.6 OCSP Signature Authority Delegation
// - The responder certificate is issued to the responder by CA
logger.log(Level.INFO, "OCSP response is signed by an authorized responder certificate");
} else {
// question."
if (!signingCert.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
logger.log(Level.INFO, "Signer certificate''s Issuer: {0}\nIssuer certificate''s Subject: {1}", new Object[] { signingCert.getIssuerX500Principal().getName(), issuerCertificate.getSubjectX500Principal().getName() });
throw new CertPathValidatorException("Responder\'s certificate is not authorized to sign OCSP responses");
}
try {
List<String> purposes = signingCert.getExtendedKeyUsage();
if (purposes == null || !purposes.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
logger.log(Level.INFO, "OCSPSigning extended usage is not set");
throw new CertPathValidatorException("Responder\'s certificate not valid for signing OCSP responses");
}
} catch (CertificateParsingException e) {
logger.log(Level.FINE, "Failed to get certificate''s extended key usage extension\n{0}", e.getMessage());
}
if (date == null) {
signingCert.checkValidity();
} else {
signingCert.checkValidity(date);
}
try {
Extension noOCSPCheck = new JcaX509CertificateHolder(signingCert).getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck);
// TODO If the extension is present, the OCSP client can trust the
// responder's certificate for the lifetime of the certificate.
logger.log(Level.INFO, "OCSP no-check extension is {0} present", noOCSPCheck == null ? "not" : "");
} catch (CertificateEncodingException e) {
logger.log(Level.FINE, "Certificate encoding exception: {0}", e.getMessage());
}
try {
signingCert.verify(issuerCertificate.getPublicKey());
logger.log(Level.INFO, "OCSP response is signed by an Authorized Responder");
} catch (GeneralSecurityException ex) {
signingCert = null;
}
}
}
if (signingCert == null) {
throw new CertPathValidatorException("Unable to verify OCSP Response\'s signature");
} else {
if (!verifySignature(basicOcspResponse, signingCert)) {
throw new CertPathValidatorException("Error verifying OCSP Response\'s signature");
} else {
Extension responseNonce = basicOcspResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
if (responseNonce != null && requestNonce != null && !Arrays.equals(requestNonce, responseNonce.getExtnValue().getOctets())) {
throw new CertPathValidatorException("Nonces do not match.");
} else {
// See Sun's OCSP implementation.
// https://www.ietf.org/rfc/rfc2560.txt, if nextUpdate is not set,
// the responder is indicating that newer update is avilable all the time
long current = date == null ? System.currentTimeMillis() : date.getTime();
Date stop = new Date(current + (long) TIME_SKEW);
Date start = new Date(current - (long) TIME_SKEW);
Iterator<SingleResp> iter = Arrays.asList(basicOcspResponse.getResponses()).iterator();
SingleResp singleRes = null;
do {
if (!iter.hasNext()) {
return;
}
singleRes = iter.next();
} while (!stop.before(singleRes.getThisUpdate()) && !start.after(singleRes.getNextUpdate() != null ? singleRes.getNextUpdate() : singleRes.getThisUpdate()));
throw new CertPathValidatorException("Response is unreliable: its validity interval is out-of-date");
}
}
}
}
Aggregations