Search in sources :

Example 1 with NameResolver

use of com.unboundid.ldap.sdk.NameResolver in project ldapsdk by pingidentity.

the class StaticUtils method getAvailableCanonicalHostNames.

/**
 * Retrieves the canonical host names for the provided set of
 * {@code InetAddress} objects.  If any of the provided addresses cannot be
 * resolved to a canonical host name (in which case the attempt to get the
 * canonical host name will return its IP address), it will be excluded from
 * the returned set.
 *
 * @param  nameResolver  The name resolver to use to obtain the canonical
 *                       host names.  If this is {@code null}, then the LDAP
 *                       SDK's default name resolver will be used.
 * @param  addresses     The set of addresses for which to obtain the
 *                       canonical host names.
 *
 * @return  A set of the canonical host names that could be obtained from the
 *          provided addresses.
 */
@NotNull()
public static Set<String> getAvailableCanonicalHostNames(@Nullable final NameResolver nameResolver, @NotNull final Collection<InetAddress> addresses) {
    final NameResolver resolver;
    if (nameResolver == null) {
        resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
    } else {
        resolver = nameResolver;
    }
    final Set<String> canonicalHostNames = new LinkedHashSet<>(computeMapCapacity(addresses.size()));
    for (final InetAddress address : addresses) {
        final String canonicalHostName = getCanonicalHostNameIfAvailable(resolver, address);
        if (canonicalHostName != null) {
            canonicalHostNames.add(canonicalHostName);
        }
    }
    return Collections.unmodifiableSet(canonicalHostNames);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InetAddress(java.net.InetAddress) NameResolver(com.unboundid.ldap.sdk.NameResolver)

Example 2 with NameResolver

use of com.unboundid.ldap.sdk.NameResolver in project ldapsdk by pingidentity.

the class DNSHostNameArgumentValueValidator method validateDNSHostName.

/**
 * Ensures that the provided name represents a valid DNS host name using the
 * provided settings.
 *
 * @param  name                    The name to validate as a DNS host name.
 * @param  allowIPAddresses        Indicates whether this validator will allow
 *                                 values that represent numeric IP addresses
 *                                 rather than DNS host names.  If this is
 *                                 {@code true}, then valid IP addresses will
 *                                 be accepted as well as valid DNS host
 *                                 names.  If this is {@code false}, then only
 *                                 valid DNS host names will be accepted.
 * @param  allowUnqualifiedNames   Indicates whether this validator will allow
 *                                 values that represent unqualified host
 *                                 names.  If this is {@code true}, then
 *                                 unqualified names will be accepted as long
 *                                 as they are otherwise acceptable.  If this
 *                                 is {@code false}, then only fully qualified
 *                                 host names will be accepted.
 * @param  allowUnresolvableNames  Indicates whether this validator will allow
 *                                 host name values that do not resolve to
 *                                 IP addresses.  If this is {@code true},
 *                                 then this validator will not attempt to
 *                                 resolve host names.  If this is
 *                                 {@code false}, then this validator will
 *                                 reject any host name that cannot be
 *                                 resolved to an IP address.
 * @param  nameResolver            The name resolver that will be used when
 *                                 attempting to resolve host names to IP
 *                                 addresses.  If this is {@code null}, then
 *                                 the LDAP SDK's default name resolver will
 *                                 be used.
 *
 * @throws  ArgumentException  If the provided name is not considered valid.
 */
public static void validateDNSHostName(@Nullable final String name, final boolean allowIPAddresses, final boolean allowUnqualifiedNames, final boolean allowUnresolvableNames, @Nullable final NameResolver nameResolver) throws ArgumentException {
    // Make sure that the provided name is not null or empty.
    if ((name == null) || name.isEmpty()) {
        throw new ArgumentException(ERR_DNS_NAME_VALIDATOR_NULL_OR_EMPTY.get());
    }
    // Make sure that the provided name does not contain consecutive periods.
    if (name.contains("..")) {
        throw new ArgumentException(ERR_DNS_NAME_VALIDATOR_CONSECUTIVE_PERIODS.get());
    }
    // that's acceptable.
    if (IPAddressArgumentValueValidator.isValidNumericIPAddress(name)) {
        if (allowIPAddresses) {
            // more validation.
            return;
        } else {
            throw new ArgumentException(ERR_DNS_NAME_VALIDATOR_IP_ADDRESS.get());
        }
    }
    // Make sure that the host name looks like it's syntactically valid.
    validateDNSHostNameSyntax(name);
    // original name contains at least one period.
    if ((!allowUnqualifiedNames) && (name.indexOf('.') < 0)) {
        throw new ArgumentException(ERR_DNS_NAME_VALIDATOR_NOT_QUALIFIED.get());
    }
    // If we should attempt to resolve the address, then do so now.
    if (!allowUnresolvableNames) {
        try {
            final NameResolver resolver;
            if (nameResolver == null) {
                resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
            } else {
                resolver = nameResolver;
            }
            resolver.getByName(name);
        } catch (final Exception e) {
            Debug.debugException(e);
            throw new ArgumentException(ERR_DNS_NAME_VALIDATOR_NOT_RESOLVABLE.get(), e);
        }
    }
}
Also used : NameResolver(com.unboundid.ldap.sdk.NameResolver)

Example 3 with NameResolver

use of com.unboundid.ldap.sdk.NameResolver in project ldapsdk by pingidentity.

the class StaticUtils method getAllLocalAddresses.

/**
 * Attempts to determine all addresses associated with the local system,
 * optionally including loopback addresses.
 *
 * @param  nameResolver     The name resolver to use to determine the local
 *                          host and loopback addresses.  If this is
 *                          {@code null}, then the LDAP SDK's default name
 *                          resolver will be used.
 * @param  includeLoopback  Indicates whether to include loopback addresses in
 *                          the set that is returned.
 *
 * @return  A set of the local addresses that were identified.
 */
@NotNull()
public static Set<InetAddress> getAllLocalAddresses(@Nullable final NameResolver nameResolver, final boolean includeLoopback) {
    final NameResolver resolver;
    if (nameResolver == null) {
        resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
    } else {
        resolver = nameResolver;
    }
    final LinkedHashSet<InetAddress> localAddresses = new LinkedHashSet<>(computeMapCapacity(10));
    try {
        final InetAddress localHostAddress = resolver.getLocalHost();
        if (includeLoopback || (!localHostAddress.isLoopbackAddress())) {
            localAddresses.add(localHostAddress);
        }
    } catch (final Exception e) {
        Debug.debugException(e);
    }
    try {
        final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (includeLoopback || (!networkInterface.isLoopback())) {
                final Enumeration<InetAddress> interfaceAddresses = networkInterface.getInetAddresses();
                while (interfaceAddresses.hasMoreElements()) {
                    final InetAddress address = interfaceAddresses.nextElement();
                    if (includeLoopback || (!address.isLoopbackAddress())) {
                        localAddresses.add(address);
                    }
                }
            }
        }
    } catch (final Exception e) {
        Debug.debugException(e);
    }
    if (includeLoopback) {
        try {
            localAddresses.add(resolver.getLoopbackAddress());
        } catch (final Exception e) {
            Debug.debugException(e);
        }
    }
    return Collections.unmodifiableSet(localAddresses);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress) NameResolver(com.unboundid.ldap.sdk.NameResolver) ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 4 with NameResolver

use of com.unboundid.ldap.sdk.NameResolver in project ldapsdk by pingidentity.

the class StaticUtils method getCanonicalHostNameIfAvailable.

/**
 * Retrieves the canonical host name for the provided address, if it can be
 * resolved to a name.
 *
 * @param  nameResolver  The name resolver to use to obtain the canonical
 *                       host name.  If this is {@code null}, then the LDAP
 *                       SDK's default name resolver will be used.
 * @param  address       The {@code InetAddress} for which to attempt to
 *                       obtain the canonical host name.
 *
 * @return  The canonical host name for the provided address, or {@code null}
 *          if it cannot be obtained (either because the attempt returns
 *          {@code null}, which shouldn't happen, or because it matches the
 *          IP address).
 */
@Nullable()
public static String getCanonicalHostNameIfAvailable(@Nullable final NameResolver nameResolver, @NotNull final InetAddress address) {
    final NameResolver resolver;
    if (nameResolver == null) {
        resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
    } else {
        resolver = nameResolver;
    }
    final String hostAddress = address.getHostAddress();
    final String trimmedHostAddress = trimInterfaceNameFromHostAddress(hostAddress);
    final String canonicalHostName = resolver.getCanonicalHostName(address);
    if ((canonicalHostName == null) || canonicalHostName.equalsIgnoreCase(hostAddress) || canonicalHostName.equalsIgnoreCase(trimmedHostAddress)) {
        return null;
    }
    return canonicalHostName;
}
Also used : NameResolver(com.unboundid.ldap.sdk.NameResolver)

Example 5 with NameResolver

use of com.unboundid.ldap.sdk.NameResolver in project ldapsdk by pingidentity.

the class SelfSignedCertificateGenerator method generateSelfSignedCertificate.

/**
 * Generates a self-signed certificate in the specified keystore.
 *
 * @param  toolName      The name of the tool for which the certificate is to
 *                       be generated.
 * @param  keyStoreFile  The path to the keystore file in which the
 *                       certificate is to be generated.  This must not be
 *                       {@code null}, and if the target file exists, then it
 *                       must be a JKS or PKCS #12 keystore.  If it does not
 *                       exist, then at least the parent directory must exist.
 * @param  keyStorePIN   The PIN needed to access the keystore.  It must not
 *                       be {@code null}.
 * @param  keyStoreType  The key store type for the keystore to be created, if
 *                       it does not already exist.  It must not be
 *                       {@code null}.
 * @param  alias         The alias to use for the certificate in the keystore.
 *                       It must not be {@code null}.
 *
 * @throws  CertException  If a problem occurs while trying to generate
 *                         self-signed certificate.
 */
public static void generateSelfSignedCertificate(@NotNull final String toolName, @NotNull final File keyStoreFile, @NotNull final String keyStorePIN, @NotNull final String keyStoreType, @NotNull final String alias) throws CertException {
    // Try to get a set of all addresses associated with the local system and
    // their corresponding canonical hostnames.
    final NameResolver nameResolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
    Set<InetAddress> localAddresses = StaticUtils.getAllLocalAddresses(nameResolver, false);
    if (localAddresses.isEmpty()) {
        localAddresses = StaticUtils.getAllLocalAddresses(nameResolver, true);
    }
    final Set<String> canonicalHostNames = StaticUtils.getAvailableCanonicalHostNames(nameResolver, localAddresses);
    // Construct a subject DN for the certificate.
    final DN subjectDN;
    if (localAddresses.isEmpty()) {
        subjectDN = new DN(new RDN("CN", toolName));
    } else {
        subjectDN = new DN(new RDN("CN", nameResolver.getCanonicalHostName(localAddresses.iterator().next())), new RDN("OU", toolName));
    }
    // Generate a timestamp that corresponds to one day ago.
    final long oneDayAgoTime = System.currentTimeMillis() - 86_400_000L;
    final Date oneDayAgoDate = new Date(oneDayAgoTime);
    final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
    final String yesterdayTimeStamp = dateFormatter.format(oneDayAgoDate);
    // Build the list of arguments to provide to the manage-certificates tool.
    final ArrayList<String> argList = new ArrayList<>(30);
    argList.add("generate-self-signed-certificate");
    argList.add("--keystore");
    argList.add(keyStoreFile.getAbsolutePath());
    argList.add("--keystore-password");
    argList.add(keyStorePIN);
    argList.add("--keystore-type");
    argList.add(keyStoreType);
    argList.add("--alias");
    argList.add(alias);
    argList.add("--subject-dn");
    argList.add(subjectDN.toString());
    argList.add("--days-valid");
    argList.add("366");
    argList.add("--validityStartTime");
    argList.add(yesterdayTimeStamp);
    argList.add("--key-algorithm");
    argList.add("RSA");
    argList.add("--key-size-bits");
    argList.add("2048");
    argList.add("--signature-algorithm");
    argList.add("SHA256withRSA");
    for (final String hostName : canonicalHostNames) {
        argList.add("--subject-alternative-name-dns");
        argList.add(hostName);
    }
    for (final InetAddress address : localAddresses) {
        argList.add("--subject-alternative-name-ip-address");
        argList.add(StaticUtils.trimInterfaceNameFromHostAddress(address.getHostAddress()));
    }
    argList.add("--key-usage");
    argList.add("digitalSignature");
    argList.add("--key-usage");
    argList.add("keyEncipherment");
    argList.add("--extended-key-usage");
    argList.add("server-auth");
    argList.add("--extended-key-usage");
    argList.add("client-auth");
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final ResultCode resultCode = ManageCertificates.main(null, output, output, argList.toArray(StaticUtils.NO_STRINGS));
    if (resultCode != ResultCode.SUCCESS) {
        throw new CertException(ERR_SELF_SIGNED_CERT_GENERATOR_ERROR_GENERATING_CERT.get(StaticUtils.toUTF8String(output.toByteArray())));
    }
}
Also used : ArrayList(java.util.ArrayList) RDN(com.unboundid.ldap.sdk.RDN) DN(com.unboundid.ldap.sdk.DN) CertException(com.unboundid.util.ssl.cert.CertException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) InetAddress(java.net.InetAddress) RDN(com.unboundid.ldap.sdk.RDN) SimpleDateFormat(java.text.SimpleDateFormat) NameResolver(com.unboundid.ldap.sdk.NameResolver) ResultCode(com.unboundid.ldap.sdk.ResultCode)

Aggregations

NameResolver (com.unboundid.ldap.sdk.NameResolver)5 InetAddress (java.net.InetAddress)3 LinkedHashSet (java.util.LinkedHashSet)2 DN (com.unboundid.ldap.sdk.DN)1 RDN (com.unboundid.ldap.sdk.RDN)1 ResultCode (com.unboundid.ldap.sdk.ResultCode)1 CertException (com.unboundid.util.ssl.cert.CertException)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 NetworkInterface (java.net.NetworkInterface)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1