use of java.security.cert.CertificateParsingException in project nifi by apache.
the class WebUtils method createClientHelper.
/**
* A helper method for creating clients. The client will be created using
* the given configuration and security context. Additionally, the client
* will be automatically configured for JSON serialization/deserialization.
*
* @param config client configuration
* @param ctx security context, which may be null for non-secure client
* creation
* @return a Client instance
*/
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
if (config != null) {
clientBuilder = clientBuilder.withConfig(config);
}
if (ctx != null) {
// custom hostname verifier that checks subject alternative names against the hostname of the URI
final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(final String hostname, final SSLSession ssls) {
try {
for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
if (peerCertificate instanceof X509Certificate) {
final X509Certificate x509Cert = (X509Certificate) peerCertificate;
final List<String> subjectAltNames = CertificateUtils.getSubjectAlternativeNames(x509Cert);
if (subjectAltNames.contains(hostname.toLowerCase())) {
return true;
}
}
}
} catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
logger.warn("Hostname Verification encountered exception verifying hostname due to: " + ex, ex);
}
return false;
}
};
clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(hostnameVerifier);
}
clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class);
return clientBuilder.build();
}
use of java.security.cert.CertificateParsingException in project jdk8u_jdk by JetBrains.
the class OCSPResponse method verify.
void verify(List<CertId> certIds, IssuerInfo issuerInfo, X509Certificate responderCert, Date date, byte[] nonce, String variant) throws CertPathValidatorException {
switch(responseStatus) {
case SUCCESSFUL:
break;
case TRY_LATER:
case INTERNAL_ERROR:
throw new CertPathValidatorException("OCSP response error: " + responseStatus, null, null, -1, BasicReason.UNDETERMINED_REVOCATION_STATUS);
case UNAUTHORIZED:
default:
throw new CertPathValidatorException("OCSP response error: " + responseStatus);
}
// certs that were supplied in the request
for (CertId certId : certIds) {
SingleResponse sr = getSingleResponse(certId);
if (sr == null) {
if (debug != null) {
debug.println("No response found for CertId: " + certId);
}
throw new CertPathValidatorException("OCSP response does not include a response for a " + "certificate supplied in the OCSP request");
}
if (debug != null) {
debug.println("Status of certificate (with serial number " + certId.getSerialNumber() + ") is: " + sr.getCertStatus());
}
}
// Locate the signer cert
if (signerCert == null) {
// of certs from the OCSP response
try {
if (issuerInfo.getCertificate() != null) {
certs.add(X509CertImpl.toImpl(issuerInfo.getCertificate()));
}
if (responderCert != null) {
certs.add(X509CertImpl.toImpl(responderCert));
}
} catch (CertificateException ce) {
throw new CertPathValidatorException("Invalid issuer or trusted responder certificate", ce);
}
if (respId.getType() == ResponderId.Type.BY_NAME) {
X500Principal rName = respId.getResponderName();
for (X509CertImpl cert : certs) {
if (cert.getSubjectX500Principal().equals(rName)) {
signerCert = cert;
break;
}
}
} else if (respId.getType() == ResponderId.Type.BY_KEY) {
KeyIdentifier ridKeyId = respId.getKeyIdentifier();
for (X509CertImpl cert : certs) {
// Match responder's key identifier against the cert's SKID
// This will match if the SKID is encoded using the 160-bit
// SHA-1 hash method as defined in RFC 5280.
KeyIdentifier certKeyId = cert.getSubjectKeyId();
if (certKeyId != null && ridKeyId.equals(certKeyId)) {
signerCert = cert;
break;
} else {
// cert's public key using the 160-bit SHA-1 method.
try {
certKeyId = new KeyIdentifier(cert.getPublicKey());
} catch (IOException e) {
// ignore
}
if (ridKeyId.equals(certKeyId)) {
signerCert = cert;
break;
}
}
}
}
}
// Check whether the signer cert returned by the responder is trusted
if (signerCert != null) {
// Check if the response is signed by the issuing CA
if (signerCert.getSubjectX500Principal().equals(issuerInfo.getName()) && signerCert.getPublicKey().equals(issuerInfo.getPublicKey())) {
if (debug != null) {
debug.println("OCSP response is signed by the target's " + "Issuing CA");
}
// cert is trusted, now verify the signed response
// Check if the response is signed by a trusted responder
} else if (signerCert.equals(responderCert)) {
if (debug != null) {
debug.println("OCSP response is signed by a Trusted " + "Responder");
}
// cert is trusted, now verify the signed response
// Check if the response is signed by an authorized responder
} else if (signerCert.getIssuerX500Principal().equals(issuerInfo.getName())) {
// Check for the OCSPSigning key purpose
try {
List<String> keyPurposes = signerCert.getExtendedKeyUsage();
if (keyPurposes == null || !keyPurposes.contains(KP_OCSP_SIGNING_OID)) {
throw new CertPathValidatorException("Responder's certificate not valid for signing " + "OCSP responses");
}
} catch (CertificateParsingException cpe) {
// assume cert is not valid for signing
throw new CertPathValidatorException("Responder's certificate not valid for signing " + "OCSP responses", cpe);
}
// Check algorithm constraints specified in security property
// "jdk.certpath.disabledAlgorithms".
AlgorithmChecker algChecker = new AlgorithmChecker(issuerInfo.getAnchor(), date, variant);
algChecker.init(false);
algChecker.check(signerCert, Collections.<String>emptySet());
// check the validity
try {
if (date == null) {
signerCert.checkValidity();
} else {
signerCert.checkValidity(date);
}
} catch (CertificateException e) {
throw new CertPathValidatorException("Responder's certificate not within the " + "validity period", e);
}
// check for revocation
//
// A CA may specify that an OCSP client can trust a
// responder for the lifetime of the responder's
// certificate. The CA does so by including the
// extension id-pkix-ocsp-nocheck.
//
Extension noCheck = signerCert.getExtension(PKIXExtensions.OCSPNoCheck_Id);
if (noCheck != null) {
if (debug != null) {
debug.println("Responder's certificate includes " + "the extension id-pkix-ocsp-nocheck.");
}
} else {
// we should do the revocation checking of the
// authorized responder in a future update.
}
// verify the signature
try {
signerCert.verify(issuerInfo.getPublicKey());
if (debug != null) {
debug.println("OCSP response is signed by an " + "Authorized Responder");
}
// cert is trusted, now verify the signed response
} catch (GeneralSecurityException e) {
signerCert = null;
}
} else {
throw new CertPathValidatorException("Responder's certificate is not authorized to sign " + "OCSP responses");
}
}
// key from the trusted responder cert
if (signerCert != null) {
// Check algorithm constraints specified in security property
// "jdk.certpath.disabledAlgorithms".
AlgorithmChecker.check(signerCert.getPublicKey(), sigAlgId, variant);
if (!verifySignature(signerCert)) {
throw new CertPathValidatorException("Error verifying OCSP Response's signature");
}
} else {
// Need responder's cert in order to verify the signature
throw new CertPathValidatorException("Unable to verify OCSP Response's signature");
}
if (nonce != null) {
if (responseNonce != null && !Arrays.equals(nonce, responseNonce)) {
throw new CertPathValidatorException("Nonces don't match");
}
}
// Check freshness of OCSPResponse
long now = (date == null) ? System.currentTimeMillis() : date.getTime();
Date nowPlusSkew = new Date(now + MAX_CLOCK_SKEW);
Date nowMinusSkew = new Date(now - MAX_CLOCK_SKEW);
for (SingleResponse sr : singleResponseMap.values()) {
if (debug != null) {
String until = "";
if (sr.nextUpdate != null) {
until = " until " + sr.nextUpdate;
}
debug.println("OCSP response validity interval is from " + sr.thisUpdate + until);
debug.println("Checking validity of OCSP response on: " + new Date(now));
}
// MAX(thisUpdate, nextUpdate) + MAX_CLOCK_SKEW ]
if (nowPlusSkew.before(sr.thisUpdate) || nowMinusSkew.after(sr.nextUpdate != null ? sr.nextUpdate : sr.thisUpdate)) {
throw new CertPathValidatorException("Response is unreliable: its validity " + "interval is out-of-date");
}
}
}
use of java.security.cert.CertificateParsingException 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 java.security.cert.CertificateParsingException 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;
}
use of java.security.cert.CertificateParsingException in project talk-android by nextcloud.
the class MainActivity method showCertificateDialog.
public void showCertificateDialog(X509Certificate cert, MagicTrustManager magicTrustManager, @Nullable SslErrorHandler sslErrorHandler) {
DateFormat formatter = DateFormat.getDateInstance(DateFormat.LONG);
String validFrom = formatter.format(cert.getNotBefore());
String validUntil = formatter.format(cert.getNotAfter());
String issuedBy = cert.getIssuerDN().toString();
String issuedFor;
try {
if (cert.getSubjectAlternativeNames() != null) {
StringBuilder stringBuilder = new StringBuilder();
for (Object o : cert.getSubjectAlternativeNames()) {
List list = (List) o;
int type = (Integer) list.get(0);
if (type == 2) {
String name = (String) list.get(1);
stringBuilder.append("[").append(type).append("]").append(name).append(" ");
}
}
issuedFor = stringBuilder.toString();
} else {
issuedFor = cert.getSubjectDN().getName();
}
@SuppressLint("StringFormatMatches") String dialogText = String.format(getResources().getString(R.string.nc_certificate_dialog_text), issuedBy, issuedFor, validFrom, validUntil);
new LovelyStandardDialog(this).setTopColorRes(R.color.nc_darkRed).setNegativeButtonColorRes(R.color.nc_darkRed).setPositiveButtonColorRes(R.color.colorPrimaryDark).setIcon(R.drawable.ic_security_white_24dp).setTitle(R.string.nc_certificate_dialog_title).setMessage(dialogText).setPositiveButton(R.string.nc_yes, v -> {
magicTrustManager.addCertInTrustStore(cert);
if (sslErrorHandler != null) {
sslErrorHandler.proceed();
}
}).setNegativeButton(R.string.nc_no, view1 -> {
if (sslErrorHandler != null) {
sslErrorHandler.cancel();
}
}).show();
} catch (CertificateParsingException e) {
Log.d(TAG, "Failed to parse the certificate");
}
}
Aggregations