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

The following examples show how to use org.bouncycastle.asn1.x509.GeneralName#iPAddress() . 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 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 2
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 3
Source File: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception {
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new org.bouncycastle.asn1.x500.X500Name(certSub),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(certSub),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );
  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);
  final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
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: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
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);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                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 ignored) {
                        }
                    }
                }
            }
        }
        return ipAddresses;
    }
 
Example 6
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket 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 7
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 8
Source File: LocalRepoKeyStore.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname)
        throws CertificateException, OperatorCreationException, IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);

    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(pubKey.getEncoded()));

    Date now = new Date(); // now

    /* force it to use a English/Gregorian dates for the cert, hardly anyone
       ever looks at the cert metadata anyway, and its very likely that they
       understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(now);
    c.add(Calendar.YEAR, 1);
    Time startTime = new Time(now, Locale.ENGLISH);
    Time endTime = new Time(c.getTime(), Locale.ENGLISH);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            subject,
            BigInteger.valueOf(rand.nextLong()),
            startTime,
            endTime,
            subject,
            subPubKeyInfo);

    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(
                new GeneralName(GeneralName.iPAddress, hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example 9
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 10
Source File: Certificates.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example 11
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher 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 12
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;
		}
		}
	}
}
 
Example 13
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 14
Source File: SSLConfigurator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private static GeneralName newGeneralName(String name) {
  int nameType = InetAddresses.isInetAddress(name) ? GeneralName.iPAddress : GeneralName.dNSName;

  return new GeneralName(nameType, name);
}
 
Example 15
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 16
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 17
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));
}