From 5a4844e307055c0ce26b58e99b7d7b485ecffd60 Mon Sep 17 00:00:00 2001 From: Chalard Jean Date: Mon, 8 Jul 2019 16:50:44 +0900 Subject: [PATCH] Cherry-pick the relevant parts of master change I566437e4fe10e1346858149120c50b3c20ca073f to avoid a conflict Test: atest FrameworksNetTests Change-Id: I7de4f67234bf97d58bddffa22272c7670398f56d --- core/java/android/net/NetworkUtils.java | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index 228e62daf2..d0f54b4c7f 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -16,10 +16,15 @@ package android.net; +import static android.system.OsConstants.AF_INET; +import static android.system.OsConstants.AF_INET6; + +import android.annotation.NonNull; import android.annotation.UnsupportedAppUsage; import android.net.shared.Inet4AddressUtils; import android.os.Build; import android.system.ErrnoException; +import android.system.Os; import android.util.Log; import android.util.Pair; @@ -454,4 +459,30 @@ public class NetworkUtils { } return routedIPCount; } + + private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6}; + + /** + * Returns true if the hostname is weakly validated. + * @param hostname Name of host to validate. + * @return True if it's a valid-ish hostname. + * + * @hide + */ + public static boolean isWeaklyValidatedHostname(@NonNull String hostname) { + // TODO(b/34953048): Use a validation method that permits more accurate, + // but still inexpensive, checking of likely valid DNS hostnames. + final String weakHostnameRegex = "^[a-zA-Z0-9_.-]+$"; + if (!hostname.matches(weakHostnameRegex)) { + return false; + } + + for (int address_family : ADDRESS_FAMILIES) { + if (Os.inet_pton(address_family, hostname) != null) { + return false; + } + } + + return true; + } }