private boolean matchesDN(X500Principal subject, GeneralNames targets) { GeneralName[] names = targets.getNames(); for (int i = 0; i != names.length; i++) { GeneralName gn = names[i]; if (gn.getTagNo() == GeneralName.directoryName) { try { if (new X500Principal(((ASN1Encodable)gn.getName()).toASN1Primitive().getEncoded()).equals(subject)) { return true; } } catch (IOException e) { } } } return false; }
private boolean matchesDN(X509Principal subject, GeneralNames targets) { GeneralName[] names = targets.getNames(); for (int i = 0; i != names.length; i++) { GeneralName gn = names[i]; if (gn.getTagNo() == GeneralName.directoryName) { try { if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive() .getEncoded()).equals(subject)) { return true; } } catch (IOException e) { } } } return false; }
protected Vector getCRLDistUrls(CRLDistPoint crlDistPoints) { Vector urls = new Vector(); if (crlDistPoints != null) { DistributionPoint[] distPoints = crlDistPoints.getDistributionPoints(); for (int i = 0; i < distPoints.length; i++) { DistributionPointName dp_name = distPoints[i].getDistributionPoint(); if (dp_name.getType() == DistributionPointName.FULL_NAME) { GeneralName[] generalNames = GeneralNames.getInstance(dp_name.getName()).getNames(); for (int j = 0; j < generalNames.length; j++) { if (generalNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) { String url = ((DERIA5String) generalNames[j].getName()).getString(); urls.add(url); } } } } } return urls; }
private boolean matchesDN(X500Name subject, GeneralNames targets) { GeneralName[] names = targets.getNames(); for (int i = 0; i != names.length; i++) { GeneralName gn = names[i]; if (gn.getTagNo() == GeneralName.directoryName) { if (X500Name.getInstance(gn.getName()).equals(subject)) { return true; } } } return false; }
public X509CRLEntryHolder getRevokedCertificate(BigInteger serialNumber) { GeneralNames currentCA = issuerName; for (Enumeration en = x509CRL.getRevokedCertificateEnumeration(); en.hasMoreElements();) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)en.nextElement(); if (entry.getUserCertificate().getValue().equals(serialNumber)) { return new X509CRLEntryHolder(entry, isIndirect, currentCA); } if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { currentCA = GeneralNames.getInstance(currentCaName.getParsedValue()); } } } return null; }
/** * Return a collection of X509CRLEntryHolder objects, giving the details of the * revoked certificates that appear on this CRL. * * @return the revoked certificates as a collection of X509CRLEntryHolder objects. */ public Collection getRevokedCertificates() { TBSCertList.CRLEntry[] entries = x509CRL.getRevokedCertificates(); List l = new ArrayList(entries.length); GeneralNames currentCA = issuerName; for (Enumeration en = x509CRL.getRevokedCertificateEnumeration(); en.hasMoreElements();) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)en.nextElement(); X509CRLEntryHolder crlEntry = new X509CRLEntryHolder(entry, isIndirect, currentCA); l.add(crlEntry); currentCA = crlEntry.getCertificateIssuer(); } return l; }
private Set loadCRLEntries() { Set entrySet = new HashSet(); Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name previousCertificateIssuer = null; // the issuer while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); entrySet.add(crlEntry); if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } } return entrySet; }
public CRLDistributionPointsImpl(X509Certificate cert) throws CertificateException, IOException { URINames = new ArrayList<>(); byte[] extVal = cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); if (extVal == null) return; CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(extVal)); DistributionPoint[] points = crlDistPoint.getDistributionPoints(); for (DistributionPoint p : points) { GeneralNames tmp = p.getCRLIssuer(); if (tmp != null) { GeneralName[] crlIssers = tmp.getNames(); for (int i = 0; i < crlIssers.length; i++) { if (crlIssers[i].getTagNo() == GeneralName.uniformResourceIdentifier) { String issuerUrl = crlIssers[i].toString(); URINames.add(issuerUrl); } } } } }
private boolean matchesDN(X500Principal subject, GeneralNames targets) { GeneralName[] names = targets.getNames(); for (int i = 0; i != names.length; i++) { GeneralName gn = names[i]; if (gn.getTagNo() == GeneralName.directoryName) { try { if (new X500Principal(((ASN1Encodable)gn.getName()).getEncoded()).equals(subject)) { return true; } } catch (IOException e) { } } } return false; }
public static List<String> extractX509CSRDnsNames(PKCS10CertificationRequest certReq) { List<String> dnsNames = 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.dNSName) { dnsNames.add(((DERIA5String) name.getName()).getString()); } } } } return dnsNames; }
public void performTest() throws Exception { DistributionPointName name = new DistributionPointName( new GeneralNames(new GeneralName(new X500Name("cn=test")))); ReasonFlags reasonFlags = new ReasonFlags(ReasonFlags.cACompromise); checkPoint(6, name, true, true, reasonFlags, true, true); checkPoint(2, name, false, false, reasonFlags, false, false); checkPoint(0, null, false, false, null, false, false); try { IssuingDistributionPoint.getInstance(new Object()); fail("getInstance() failed to detect bad object."); } catch (IllegalArgumentException e) { // expected } }
@Override public Attribute getValue() { try { X509Certificate cert = (X509Certificate) certificates[0]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_1); byte[] hash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(cert.getSubjectDN().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serial = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serial); ESSCertID essCertId = new ESSCertID(hash, issuerSerial); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)}))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } }
@Override public Attribute getValue() throws SignerException { try { X509Certificate cert = (X509Certificate) certificates[0]; X509Certificate issuerCert = (X509Certificate) certificates[1]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256); byte[] certHash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber); AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);// SHA-256 ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial); // return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(essCertIDv2))); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence( new ASN1Encodable[] { new DERSequence(essCertIDv2) }))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } }
/** * Get a formatted string value for the supplied general names object. * * @param generalNames General names * @return Formatted string * @throws IOException */ private String getGeneralNamesString(GeneralNames generalNames, LinkClass linkClass) throws IOException { GeneralName[] names = generalNames.getNames(); StringBuilder strBuff = new StringBuilder(); strBuff.append("<ul>"); for (GeneralName name : names) { strBuff.append("<li>"); strBuff.append(getGeneralNameString(name, linkClass)); strBuff.append("</li>"); } strBuff.append("</ul>"); return strBuff.toString(); }
/** * Returns additional Subject Alternative Names for service certificates. */ public GeneralNames getSANs() { List<GeneralName> generalNames = new ArrayList<>(); generalNames.add(new GeneralName(GeneralName.dNSName, autoIpHostname)); // Process VIP names, if any vipSpecs.stream() .map(vipSpec -> new GeneralName( GeneralName.dNSName, EndpointUtils.toVipHostname( serviceName, new EndpointUtils.VipInfo(vipSpec.getVipName(), (int) vipSpec.getPort())))) .forEach(vipGeneralName -> generalNames.add(vipGeneralName)); return new GeneralNames(generalNames.toArray(new GeneralName[generalNames.size()])); }
@Test public void testGetSANs() throws Exception { CertificateNamesGenerator certificateNamesGenerator = new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance); GeneralNames sans = certificateNamesGenerator.getSANs(); Assert.assertEquals(1, sans.getNames().length); List<String> names = Arrays.stream(sans.getNames()) .map(name -> name.getName().toString()) .collect(Collectors.toList()); Assert.assertEquals(1, names.size()); Assert.assertTrue(names.contains(taskDnsName(TestConstants.TASK_NAME, TestConstants.SERVICE_NAME))); Assert.assertFalse(names.contains(taskDnsName("*", TestConstants.SERVICE_NAME))); Assert.assertFalse(names.contains(taskVipName("*", TestConstants.SERVICE_NAME))); // echo -n "some-pod-test-task-name.service-name.autoip.dcos.thisdcos.directory" | sha1sum Assert.assertEquals("a22fd2735aae7c55e47bece5f6c10612866583bf", certificateNamesGenerator.getSANsHash()); }
@Test public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() { final String distinguishedName = "O=test-org, ST=Jupiter, C=MilkyWay, CN=test-common-name, OU=test-org-unit, L=Europa"; final GeneralNames generalNames = new GeneralNames( new GeneralName(GeneralName.dNSName, "SolarSystem")); CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.BIG_TEST_CERT); assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName)); assertThat(certificateReader.getKeyLength(), equalTo(4096)); assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames)); assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()), containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth)); assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature), equalTo(true)); assertThat(certificateReader.getDurationDays(), equalTo(30)); assertThat(certificateReader.isSelfSigned(), equalTo(false)); assertThat(certificateReader.isCa(), equalTo(false)); }
@Test public void testVipsAddedAsSans() { Mockito.when(mockResourceSet.getResources()).thenReturn(Collections.singletonList(mockVIPSpec)); Mockito.when(mockVIPSpec.getVipName()).thenReturn("test-vip"); Mockito.when(mockVIPSpec.getPort()).thenReturn(8000L); CertificateNamesGenerator certificateNamesGenerator = new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance); GeneralNames sans = certificateNamesGenerator.getSANs(); Assert.assertEquals(2, sans.getNames().length); List<String> names = Arrays.stream(sans.getNames()) .map(name -> name.getName().toString()) .collect(Collectors.toList()); Assert.assertEquals(2, names.size()); Assert.assertTrue(names.contains(taskDnsName(TestConstants.TASK_NAME, TestConstants.SERVICE_NAME))); Assert.assertTrue(names.contains(taskVipName("test-vip", TestConstants.SERVICE_NAME))); // echo -n "some-pod-test-task-name.service-name.autoip.dcos.thisdcos.directory;test-vip.service-name.l4lb.thisdcos.directory" | sha1sum Assert.assertEquals("99f8ec48101c439ce41eb62662056dc0ff5d227a", certificateNamesGenerator.getSANsHash()); }
private static X509Certificate createSelfSignedCertificate(KeyPair keyPair, ConfigserverConfig config) throws IOException, CertificateException, OperatorCreationException { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate()); X500Name x500Name = new X500Name("CN="+ config.loadBalancerAddress()); Instant now = Instant.now(); Date notBefore = Date.from(now); Date notAfter = Date.from(now.plus(Duration.ofDays(30))); GeneralNames generalNames = new GeneralNames( config.zookeeperserver().stream() .map(server -> new GeneralName(GeneralName.dNSName, server.hostname())) .toArray(GeneralName[]::new)); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic() ) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.subjectAlternativeName, false, generalNames); return new JcaX509CertificateConverter() .setProvider(provider) .getCertificate(certificateBuilder.build(contentSigner)); }
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; }
private GeneralNames buildAlternativeNames(CertificateGenerationRequestParameters params) { String[] alternativeNamesList = params.getAlternativeNames(); if (alternativeNamesList == null){ return null; } GeneralNamesBuilder builder = new GeneralNamesBuilder(); for (String name :alternativeNamesList) { if (InetAddresses.isInetAddress(name)) { builder.addName(new GeneralName(GeneralName.iPAddress, name)); } else { builder.addName(new GeneralName(GeneralName.dNSName, name)); } } return builder.build(); }
/** * 动态生成服务器证书,并进行CA签授 * * @param issuer 颁发机构 */ public static X509Certificate genCert(String issuer, PrivateKey caPriKey, Date caNotBefore, Date caNotAfter, PublicKey serverPubKey, String... hosts) throws Exception { /* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot"; String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/ //根据CA证书subject来动态生成目标服务器证书的issuer和subject String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + hosts[0]; //doc from https://www.cryptoworkshop.com/guide/ JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(issuer), //issue#3 修复ElementaryOS上证书不安全问题(serialNumber为1时证书会提示不安全),避免serialNumber冲突,采用时间戳+4位随机数生成 BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000), caNotBefore, caNotAfter, new X500Name(subject), serverPubKey); //SAN扩展证书支持的域名,否则浏览器提示证书不安全 GeneralName[] generalNames = new GeneralName[hosts.length]; for (int i = 0; i < hosts.length; i++) { generalNames[i] = new GeneralName(GeneralName.dNSName, hosts[i]); } GeneralNames subjectAltName = new GeneralNames(generalNames); jv3Builder.addExtension(Extension.subjectAlternativeName, false, subjectAltName); //SHA256 用SHA1浏览器可能会提示证书不安全 ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPriKey); return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer)); }
public AttributeCertificateHolder(X509Principal issuerName, BigInteger serialNumber) { holder = new org.bouncycastle.asn1.x509.Holder(new IssuerSerial( GeneralNames.getInstance(new DERSequence(new GeneralName(issuerName))), new ASN1Integer(serialNumber))); }
private Principal[] getPrincipals(GeneralNames names) { Object[] p = this.getNames(names.getNames()); List l = new ArrayList(); for (int i = 0; i != p.length; i++) { if (p[i] instanceof Principal) { l.add(p[i]); } } return (Principal[])l.toArray(new Principal[l.size()]); }
public AttributeCertificateHolder(X500Name issuerName, BigInteger serialNumber) { holder = new Holder(new IssuerSerial( new GeneralNames(new GeneralName(issuerName)), new ASN1Integer(serialNumber))); }