Java Code Examples for org.bouncycastle.asn1.x509.GeneralName#dNSName()

The following examples show how to use org.bouncycastle.asn1.x509.GeneralName#dNSName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example 2
Source File: CertificateReaderTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void returnsParametersCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(BIG_TEST_CERT);

  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.getSubjectName().toString(), equalTo(distinguishedName));
}
 
Example 3
Source File: CertificateReaderTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(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));
}
 
Example 4
Source File: SubjectAlternativeName.java    From vespa with Apache License 2.0 6 votes vote down vote up
private String getValue(GeneralName bcGeneralName) {
    ASN1Encodable name = bcGeneralName.getName();
    switch (bcGeneralName.getTagNo()) {
        case GeneralName.rfc822Name:
        case GeneralName.dNSName:
        case GeneralName.uniformResourceIdentifier:
            return DERIA5String.getInstance(name).getString();
        case GeneralName.directoryName:
            return X500Name.getInstance(name).toString();
        case GeneralName.iPAddress:
            byte[] octets = DEROctetString.getInstance(name.toASN1Primitive()).getOctets();
            try {
                return InetAddress.getByAddress(octets).getHostAddress();
            } catch (UnknownHostException e) {
                // Only thrown if IP address is of invalid length, which is an illegal argument
                throw new IllegalArgumentException(e);
            }
        default:
            return name.toString();
    }
}
 
Example 5
Source File: Certificate.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException {
    X500Name issuerName = new X500Name("CN=bouncrca");
    X500Name subjectName = new X500Name("CN=bouncr");
    BigInteger serial = BigInteger.valueOf(2);
    long t1 = System.currentTimeMillis();
    KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
    rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking"));
    KeyPair kp = rsa.generateKeyPair();
    System.out.println(System.currentTimeMillis() - t1);

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic());
    DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] {
            new GeneralName(GeneralName.dNSName, "localhost"),
            new GeneralName(GeneralName.dNSName, "127.0.0.1")
    });
    builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);
    X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate());

    return new X500PrivateCredential(cert, kp.getPrivate());
}
 
Example 6
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example 7
Source File: SubjectAlternativeNameImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
public SubjectAlternativeNameImpl(X509Certificate cert) throws IOException {
	DNSNames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.subjectAlternativeName.getId());
	if (extVal == null)
		return;
	GeneralNames gn = GeneralNames.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	GeneralName[] names = gn.getNames();
	for (GeneralName name : names) {
		if (name.getTagNo() == GeneralName.dNSName) {
			String dns = name.getName().toString();
			DNSNames.add(dns);
		}
	}
}
 
Example 8
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddrAndDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName[] {
            new GeneralName( GeneralName.otherName, otherName ),
            new GeneralName( GeneralName.dNSName, subjectAltNameDNS )
    });
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 2, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example 9
Source File: CertUtilsTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateCertificate() throws Exception {
    final KeyPair clientKeyPair = CertUtils.generateRandomKeyPair(1024);
    final List<String> domainNames = Arrays.asList("domain1.com", "www.2.domain2.com", "3.domain3.com");
    final List<String> addressList = Arrays.asList("1.2.3.4", "192.168.1.1", "2a02:120b:2c16:f6d0:d9df:8ebc:e44a:f181");

    final X509Certificate clientCert = CertUtils.generateV3Certificate(caCertificate, caKeyPair, clientKeyPair.getPublic(),
            "CN=domain.example", "SHA256WithRSAEncryption", 10, domainNames, addressList);

    clientCert.verify(caKeyPair.getPublic());
    Assert.assertEquals(clientCert.getIssuerDN(), caCertificate.getIssuerDN());
    Assert.assertEquals(clientCert.getSigAlgName(), "SHA256WITHRSA");
    Assert.assertArrayEquals(clientCert.getPublicKey().getEncoded(), clientKeyPair.getPublic().getEncoded());
    Assert.assertNotNull(clientCert.getSubjectAlternativeNames());

    for (final List<?> altNames : clientCert.getSubjectAlternativeNames()) {
        Assert.assertTrue(altNames.size() == 2);
        final Object first = altNames.get(0);
        final Object second = altNames.get(1);
        if (first instanceof Integer && ((Integer) first) == GeneralName.iPAddress) {
            Assert.assertTrue(addressList.contains((String) second));
        }
        if (first instanceof Integer && ((Integer) first) == GeneralName.dNSName) {
            Assert.assertTrue(domainNames.contains((String) second));
        }
    }
}
 
Example 10
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Converts a list of domain name Subject Alternative Names into ASN1Encodable GeneralNames objects, for use with
 * the Bouncy Castle certificate builder.
 *
 * @param subjectAlternativeNames domain name SANs to convert
 * @return a GeneralNames instance that includes the specifie dsubjectAlternativeNames as DNS name fields
 */
private static GeneralNames getDomainNameSANsAsASN1Encodable(List<String> subjectAlternativeNames) {
    List<GeneralName> encodedSANs = new ArrayList<>(subjectAlternativeNames.size());
    for (String subjectAlternativeName : subjectAlternativeNames) {
        // IP addresses use the IP Address tag instead of the DNS Name tag in the SAN list
        boolean isIpAddress = InetAddresses.isInetAddress(subjectAlternativeName);
        GeneralName generalName = new GeneralName(isIpAddress ? GeneralName.iPAddress : GeneralName.dNSName, subjectAlternativeName);
        encodedSANs.add(generalName);
    }

    return new GeneralNames(encodedSANs.toArray(new GeneralName[encodedSANs.size()]));
}
 
Example 11
Source File: InstanceClientRegister.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateCSR(String domainName, String serviceName,
        String instanceId, String dnsSuffix, PrivateKey key) {
    
    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
    
    // now let's generate our dsnName field based on our principal's details
    
    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
    
    // next we include our instance id
    
    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);
    
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
    
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }
    
    return csr;
}
 
Example 12
Source File: TLSCertificateBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private void addSAN(X509v3CertificateBuilder certBuilder, String san) throws CertIOException {
    ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[]{new GeneralName(GeneralName.dNSName, san)};
    certBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(subjectAlternativeNames));
}
 
Example 13
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private Certificate generateCertificateUsingCsr(final String csr, final List<String> names, final List<String> ips, final int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException, SignatureException, IOException, OperatorCreationException {
    final List<String> dnsNames = new ArrayList<>();
    final List<String> ipAddresses = new ArrayList<>();

    if (names != null) {
        dnsNames.addAll(names);
    }
    if (ips != null) {
        ipAddresses.addAll(ips);
    }

    PemObject pemObject = null;

    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }

    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }

    final JcaPKCS10CertificationRequest request = new JcaPKCS10CertificationRequest(pemObject.getContent());
    final String subject = request.getSubject().toString();
    for (final Attribute attribute : request.getAttributes()) {
        if (attribute == null) {
            continue;
        }
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            final Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            final GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns != null && gns.getNames() != null && gns.getNames().length > 0) {
                for (final GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.dNSName) {
                        dnsNames.add(name.getName().toString());
                    }
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        final InetAddress address = InetAddress.getByAddress(DatatypeConverter.parseHexBinary(name.getName().toString().substring(1)));
                        ipAddresses.add(address.toString().replace("/", ""));
                    }
                }
            }
        }
    }

    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(
            caCertificate, caKeyPair, request.getPublicKey(),
            subject, CAManager.CertSignatureAlgorithm.value(),
            validityDays, dnsNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}
 
Example 14
Source File: TlsUtils.java    From tessera with Apache License 2.0 4 votes vote down vote up
default void generateKeyStoreWithSelfSignedCertificate(String address, Path privateKeyFile, char[] password)
        throws NoSuchAlgorithmException, IOException, OperatorCreationException, CertificateException,
                InvalidKeyException, NoSuchProviderException, SignatureException, KeyStoreException {

    final SecureRandom secureRandom = new SecureRandom();

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ENCRYPTION);
    keyGen.initialize(2048, secureRandom);
    KeyPair keypair = keyGen.generateKeyPair();
    final PublicKey publicKey = keypair.getPublic();
    final PrivateKey privateKey = keypair.getPrivate();
    final String cnString = address.replaceFirst("^(http[s]?://www\\.|http[s]?://|www\\.)", "");
    final X500Name commonName = new X500Name(COMMON_NAME_STRING + cnString);
    Date startDate = new Date(System.currentTimeMillis());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    calendar.add(Calendar.YEAR, 1);
    Date endDate = calendar.getTime();

    X509v3CertificateBuilder builder =
            new JcaX509v3CertificateBuilder(
                    commonName, new BigInteger(64, secureRandom), startDate, endDate, commonName, publicKey);

    GeneralName[] subjectAlternativeNames =
            new GeneralName[] {
                new GeneralName(GeneralName.dNSName, LOCALHOST),
                new GeneralName(GeneralName.dNSName, HostnameUtil.create().getHostName()),
                new GeneralName(GeneralName.iPAddress, LOCALHOST_IP),
                new GeneralName(GeneralName.iPAddress, LOCALHOST_IP_2),
                new GeneralName(GeneralName.iPAddress, HostnameUtil.create().getHostIpAddress())
            };

    builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(subjectAlternativeNames));

    ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(privateKey);
    X509CertificateHolder certHolder = builder.build(contentSigner);
    X509Certificate certificate =
            new JcaX509CertificateConverter().setProvider(provider).getCertificate(certHolder);

    certificate.verify(publicKey);

    KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
    keyStore.load(null, null);
    keyStore.setKeyEntry("tessera", privateKey, password, new X509Certificate[] {certificate});

    try (OutputStream keyStoreFile = Files.newOutputStream(privateKeyFile)) {
        keyStore.store(keyStoreFile, password);
    }
}
 
Example 15
Source File: CertificateAuthority.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * 証明書署名要求から Subject Alternative Names (SANs) を取得する.
 *
 * @param request 証明書署名要求
 * @return SubjectAlternativeNamesを示す {@link GeneralNames} オブジェクト
 * @throws IOException 解析に失敗した場合
 */
private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException {
    List<ASN1Encodable> generalNames = new ArrayList<>();

    CertificationRequestInfo info = request.getCertificationRequestInfo();
    ASN1Set attributes = info.getAttributes();
    for (int i = 0; i < attributes.size(); i++) {
        DEREncodable extensionRequestObj = attributes.getObjectAt(i);
        if (!(extensionRequestObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensionRequest = (DERSequence) extensionRequestObj;
        if (extensionRequest.size() != 2) {
            continue;
        }
        DEREncodable idObj = extensionRequest.getObjectAt(0);
        DEREncodable contentObj = extensionRequest.getObjectAt(1);
        if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) {
            continue;
        }
        ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj;
        DERSet content = (DERSet) contentObj;
        if (!id.getId().equals("1.2.840.113549.1.9.14")) {
            continue;
        }
        if (content.size() < 1) {
            continue;
        }
        DEREncodable extensionsObj = content.getObjectAt(0);
        if (!(extensionsObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensions = (DERSequence) extensionsObj;

        for (int k = 0; k < extensions.size(); k++) {
            DEREncodable extensionObj = extensions.getObjectAt(k);
            if (!(extensionObj instanceof DERSequence)) {
                continue;
            }
            DERSequence extension = (DERSequence) extensionObj;
            if (extension.size() != 2) {
                continue;
            }
            DEREncodable extensionIdObj = extension.getObjectAt(0);
            DEREncodable extensionContentObj = extension.getObjectAt(1);
            if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) {
                continue;
            }
            ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj;
            if (extensionId.getId().equals("2.5.29.17")) {
                DEROctetString san = (DEROctetString) extensionContentObj;

                ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream());
                DEREncodable namesObj = sanParser.readObject().getDERObject();
                if (namesObj instanceof DERSequence) {
                    DERSequence names = (DERSequence) namesObj;
                    for (int m = 0; m < names.size(); m++) {
                        DEREncodable nameObj = names.getObjectAt(m);
                        if (nameObj instanceof DERTaggedObject) {
                            DERTaggedObject name = (DERTaggedObject) nameObj;
                            switch (name.getTagNo()) {
                                case GeneralName.dNSName:
                                    generalNames.add(new GeneralName(GeneralName.dNSName, DERIA5String.getInstance(name, false)));
                                    break;
                                case GeneralName.iPAddress:
                                    generalNames.add(new GeneralName(GeneralName.iPAddress, DEROctetString.getInstance(name, true)));
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (generalNames.size() > 0) {
        return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[0])));
    }
    return null;
}
 
Example 16
Source File: ZTSInstanceRegister.java    From athenz with Apache License 2.0 4 votes vote down vote up
private static InstanceRegisterInformation generateInstanceRegisterInfo(final String domainName,
        final String serviceName, PrivateKey privateKey, final String serviceToken,
        final String csrDn, final String csrDomain) {

    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }

    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }

    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name

    final String domain = domainName.toLowerCase();
    final String service = serviceName.toLowerCase();
    final String cn = domain + "." + service;

    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }

    // now let's generate our dsnName field based on our principal's details

    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    final String instanceUri = "athenz://instanceid/" + domain + "/" + service;
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(instanceUri));

    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    return new InstanceRegisterInformation().setCsr(csr).setProvider("sys.auth.zts")
            .setDomain(domain).setService(service).setAttestationData(serviceToken);
}
 
Example 17
Source File: ZTSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
/**
 * Generate a Role Certificate request that could be sent to ZTS
 * to obtain a X509 Certificate for the requested role.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param roleDomainName name of the domain where role is defined
 * @param roleName name of the role to get a certificate request for
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return RoleCertificateRequest object
 */
static public RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain,
        final String principalService, final String roleDomainName, final String roleName,
        PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {
    
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    
    if (roleDomainName == null || roleName == null) {
        throw new IllegalArgumentException("Role DomainName and Name must be specified");
    }
    
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be our role resource value
    
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    
    String dn = "cn=" + roleDomainName.toLowerCase() + AuthorityConsts.ROLE_SEP + roleName.toLowerCase();
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    
    // now let's generate our dsnName and email fields which will based on
    // our principal's details

    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    final String email = domain + "." + service + "@" + csrDomain;
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email));
    
    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    return new RoleCertificateRequest().setCsr(csr).setExpiryTime((long) expiryTime);
}
 
Example 18
Source File: ZTSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
/**
 * Generate a Instance Refresh request that could be sent to ZTS to
 * request a TLS certificate for a service.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return InstanceRefreshRequest object
 */
static public InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain,
        final String principalService, PrivateKey privateKey, final String csrDn,
        final String csrDomain, int expiryTime) {
    
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name
    
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    final String cn = domain + "." + service;
    
    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    
    // now let's generate our dsnName field based on our principal's details

    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    
    GeneralName[] sanArray = new GeneralName[1];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    
    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    return new InstanceRefreshRequest().setCsr(csr).setExpiryTime(expiryTime);
}
 
Example 19
Source File: DefaultProfile.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean validateGeneralName(int type, String value) {
  // TODO : We should add more validation for IP address, for example
  //  it matches the local network, and domain matches where the cluster
  //  exits.
  if (!isSupportedGeneralName(type)) {
    return false;
  }
  switch (type) {
  case GeneralName.iPAddress:

    // We need DatatypeConverter conversion, since the original CSR encodes
    // an IP address int a Hex String, for example 8.8.8.8 is encoded as
    // #08080808. Value string is always preceded by "#", we will strip
    // that before passing it on.

    // getByAddress call converts the IP address to hostname/ipAddress format.
    // if the hostname cannot determined then it will be /ipAddress.

    // TODO: Fail? if we cannot resolve the Hostname?
    try {
      final InetAddress byAddress = InetAddress.getByAddress(
          Hex.decodeHex(value.substring(1)));
      if (LOG.isDebugEnabled()) {
        LOG.debug("Host Name/IP Address : {}", byAddress.toString());
      }
      return true;
    } catch (UnknownHostException | DecoderException e) {
      return false;
    }
  case GeneralName.dNSName:
    return DomainValidator.getInstance().isValid(value);
  case GeneralName.otherName:
    // for other name its a general string, nothing to validate
    return true;
  default:
    // This should not happen, since it guarded via isSupportedGeneralName.
    LOG.error("Unexpected type in General Name (int value) : {}", type);
    return false;
  }
}
 
Example 20
Source File: DGeneralNameChooser.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private void populate(GeneralName generalName) {
	if (generalName == null) {
		jrbDirectoryName.setSelected(true);
	} else {
		switch (generalName.getTagNo()) {
		case GeneralName.directoryName: {
			jrbDirectoryName.setSelected(true);
			jdnDirectoryName.setDistinguishedName((X500Name) generalName.getName());
			break;
		}
		case GeneralName.dNSName: {
			jrbDnsName.setSelected(true);
			jtfDnsName.setText(((DERIA5String) generalName.getName()).getString());
			break;
		}
		case GeneralName.iPAddress: {
			jrbIpAddress.setSelected(true);
			byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();
			try {
				jtfIpAddress.setText(InetAddress.getByAddress(ipAddressBytes).getHostAddress());
			} catch (UnknownHostException e) {
				// cannot happen here because user input was checked for validity
			}
			break;
		}
		case GeneralName.registeredID: {
			jrbRegisteredId.setSelected(true);
			joiRegisteredId.setObjectId((ASN1ObjectIdentifier) generalName.getName());
			break;
		}
		case GeneralName.rfc822Name: {
			jrbRfc822Name.setSelected(true);
			jtfRfc822Name.setText(((DERIA5String) generalName.getName()).getString());
			break;
		}
		case GeneralName.uniformResourceIdentifier: {
			jrbUniformResourceIdentifier.setSelected(true);
			jtfUniformResourceIdentifier.setText(((DERIA5String) generalName.getName()).getString());
			break;
		}
		case GeneralName.otherName: {
			jrbPrincipalName.setSelected(true);
			// we currently only support UPN in otherName
			jtfPrincipalName.setText(GeneralNameUtil.parseUPN(generalName));
			break;
		}
		}
	}
}