Merge "Split NetworkUtils and NetworkUtilsInternal" am: 3ed4fd3a89

Original change: https://android-review.googlesource.com/c/platform/frameworks/base/+/1513140

MUST ONLY BE SUBMITTED BY AUTOMERGER

Change-Id: Iaa5503f829077f70803e2e865f58c6e4691d1a73
This commit is contained in:
Remi NGUYEN VAN
2020-12-23 01:37:12 +00:00
committed by Automerger Merge Worker
14 changed files with 232 additions and 146 deletions

View File

@@ -53,7 +53,6 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ParceledListSlice;
import android.content.pm.UserInfo;
import android.graphics.Bitmap;
import android.net.NetworkUtils;
import android.net.PrivateDnsConnectivityChecker;
import android.net.ProxyInfo;
import android.net.Uri;
@@ -90,6 +89,7 @@ import android.util.ArraySet;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.net.NetworkUtilsInternal;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.Preconditions;
import com.android.org.conscrypt.TrustedCertificateStore;
@@ -11466,7 +11466,7 @@ public class DevicePolicyManager {
return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
}
if (NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
}

View File

@@ -26,9 +26,9 @@ import static android.net.NetworkStatsHistory.DataStreamUtils.writeVarLongArray;
import static android.net.NetworkStatsHistory.Entry.UNKNOWN;
import static android.net.NetworkStatsHistory.ParcelUtils.readLongArray;
import static android.net.NetworkStatsHistory.ParcelUtils.writeLongArray;
import static android.net.NetworkUtils.multiplySafeByRational;
import static android.text.format.DateUtils.SECOND_IN_MILLIS;
import static com.android.internal.net.NetworkUtilsInternal.multiplySafeByRational;
import static com.android.internal.util.ArrayUtils.total;
import android.compat.annotation.UnsupportedAppUsage;

View File

@@ -16,14 +16,9 @@
package android.net;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import android.annotation.NonNull;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.system.ErrnoException;
import android.system.Os;
import android.util.Log;
import android.util.Pair;
@@ -154,14 +149,6 @@ public class NetworkUtils {
*/
public static native Network getDnsNetwork() throws ErrnoException;
/**
* Allow/Disallow creating AF_INET/AF_INET6 sockets and DNS lookups for current process.
*
* @param allowNetworking whether to allow or disallow creating AF_INET/AF_INET6 sockets
* and DNS lookups.
*/
public static native void setAllowNetworkingForProcess(boolean allowNetworking);
/**
* Get the tcp repair window associated with the {@code fd}.
*
@@ -437,60 +424,4 @@ 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;
}
/**
* Safely multiple a value by a rational.
* <p>
* Internally it uses integer-based math whenever possible, but switches
* over to double-based math if values would overflow.
* @hide
*/
public static long multiplySafeByRational(long value, long num, long den) {
if (den == 0) {
throw new ArithmeticException("Invalid Denominator");
}
long x = value;
long y = num;
// Logic shamelessly borrowed from Math.multiplyExact()
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if (((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if (((y != 0) && (r / y != x)) ||
(x == Long.MIN_VALUE && y == -1)) {
// Use double math to avoid overflowing
return (long) (((double) num / den) * value);
}
}
return r / den;
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.net;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import android.annotation.NonNull;
import android.system.Os;
/** @hide */
public class NetworkUtilsInternal {
private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6};
/**
* Allow/Disallow creating AF_INET/AF_INET6 sockets and DNS lookups for current process.
*
* @param allowNetworking whether to allow or disallow creating AF_INET/AF_INET6 sockets
* and DNS lookups.
*/
public static native void setAllowNetworkingForProcess(boolean allowNetworking);
/**
* 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;
}
/**
* Safely multiple a value by a rational.
* <p>
* Internally it uses integer-based math whenever possible, but switches
* over to double-based math if values would overflow.
* @hide
*/
public static long multiplySafeByRational(long value, long num, long den) {
if (den == 0) {
throw new ArithmeticException("Invalid Denominator");
}
long x = value;
long y = num;
// Logic shamelessly borrowed from Math.multiplyExact()
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if (((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if (((y != 0) && (r / y != x))
|| (x == Long.MIN_VALUE && y == -1)) {
// Use double math to avoid overflowing
return (long) (((double) num / den) * value);
}
}
return r / den;
}
}

View File

@@ -24,7 +24,6 @@ import android.content.pm.ApplicationInfo;
import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.NetworkUtils;
import android.os.FactoryTest;
import android.os.IVold;
import android.os.Process;
@@ -35,6 +34,8 @@ import android.system.ErrnoException;
import android.system.Os;
import android.util.Log;
import com.android.internal.net.NetworkUtilsInternal;
import dalvik.annotation.optimization.FastNative;
import dalvik.system.ZygoteHooks;
@@ -352,7 +353,7 @@ public final class Zygote {
// If no GIDs were specified, don't make any permissions changes based on groups.
if (gids != null && gids.length > 0) {
NetworkUtils.setAllowNetworkingForProcess(containsInetGid(gids));
NetworkUtilsInternal.setAllowNetworkingForProcess(containsInetGid(gids));
}
}

View File

@@ -182,6 +182,7 @@ cc_library_shared {
"android_content_res_Configuration.cpp",
"android_security_Scrypt.cpp",
"com_android_internal_content_om_OverlayConfig.cpp",
"com_android_internal_net_NetworkUtilsInternal.cpp",
"com_android_internal_os_ClassLoaderFactory.cpp",
"com_android_internal_os_FuseAppLoop.cpp",
"com_android_internal_os_KernelCpuUidBpfMapReader.cpp",

View File

@@ -187,6 +187,7 @@ extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
extern int register_android_security_Scrypt(JNIEnv *env);
extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env);
extern int register_com_android_internal_content_om_OverlayConfig(JNIEnv *env);
extern int register_com_android_internal_net_NetworkUtilsInternal(JNIEnv* env);
extern int register_com_android_internal_os_ClassLoaderFactory(JNIEnv* env);
extern int register_com_android_internal_os_FuseAppLoop(JNIEnv* env);
extern int register_com_android_internal_os_KernelCpuUidBpfMapReader(JNIEnv *env);
@@ -1520,6 +1521,7 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_os_SharedMemory),
REG_JNI(register_android_os_incremental_IncrementalManager),
REG_JNI(register_com_android_internal_content_om_OverlayConfig),
REG_JNI(register_com_android_internal_net_NetworkUtilsInternal),
REG_JNI(register_com_android_internal_os_ClassLoaderFactory),
REG_JNI(register_com_android_internal_os_Zygote),
REG_JNI(register_com_android_internal_os_ZygoteInit),

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2008, The Android Open Source Project
* Copyright 2020, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@
#include <netinet/udp.h>
#include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
#include <android_runtime/AndroidRuntime.h>
#include <cutils/properties.h>
#include <nativehelper/JNIPlatformHelp.h>
#include <nativehelper/ScopedLocalRef.h>
@@ -226,11 +225,6 @@ static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jobject thiz) {
class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
}
static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
jboolean hasConnectivity) {
setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
}
static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
if (javaFd == NULL) {
jniThrowNullPointerException(env, NULL);
@@ -288,7 +282,6 @@ static const JNINativeMethod gNetworkUtilMethods[] = {
{ "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
{ "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
{ "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
{ "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },
};
// clang-format on

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2020, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NetdClient.h"
#include "core_jni_helpers.h"
#include "jni.h"
namespace android {
static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
jboolean hasConnectivity) {
setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
}
static const JNINativeMethod gNetworkUtilMethods[] = {
{"setAllowNetworkingForProcess", "(Z)V",
(void *)android_net_utils_setAllowNetworkingForProcess},
};
int register_com_android_internal_net_NetworkUtilsInternal(JNIEnv *env) {
return RegisterMethodsOrDie(env, "com/android/internal/net/NetworkUtilsInternal",
gNetworkUtilMethods, NELEM(gNetworkUtilMethods));
}
} // namespace android

View File

@@ -28,9 +28,9 @@ import static android.net.NetworkStats.SET_DEFAULT;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static android.net.TrafficStats.UID_REMOVED;
import static android.net.NetworkUtils.multiplySafeByRational;
import static android.text.format.DateUtils.WEEK_IN_MILLIS;
import static com.android.internal.net.NetworkUtilsInternal.multiplySafeByRational;
import static com.android.server.net.NetworkStatsService.TAG;
import android.net.NetworkIdentity;

View File

@@ -195,7 +195,6 @@ import android.media.AudioManager;
import android.media.IAudioService;
import android.net.ConnectivityManager;
import android.net.IIpConnectivityMetrics;
import android.net.NetworkUtils;
import android.net.ProxyInfo;
import android.net.Uri;
import android.net.metrics.IpConnectivityLog;
@@ -267,6 +266,7 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.compat.IPlatformCompat;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.net.NetworkUtilsInternal;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.os.BackgroundThread;
import com.android.internal.statusbar.IStatusBarService;
@@ -15540,7 +15540,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
return PRIVATE_DNS_SET_NO_ERROR;
case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
if (TextUtils.isEmpty(privateDnsHost)
|| !NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
|| !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
throw new IllegalArgumentException(
String.format("Provided hostname %s is not valid", privateDnsHost));
}

View File

@@ -16,24 +16,10 @@
package android.net;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import static android.system.OsConstants.AF_UNIX;
import static android.system.OsConstants.EPERM;
import static android.system.OsConstants.SOCK_DGRAM;
import static android.system.OsConstants.SOCK_STREAM;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.fail;
import android.system.ErrnoException;
import android.system.Os;
import androidx.test.runner.AndroidJUnit4;
import libcore.io.IoUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -139,50 +125,4 @@ public class NetworkUtilsTest {
assertEquals(BigInteger.valueOf(7l - 4 + 4 + 16 + 65536),
NetworkUtils.routedIPv6AddressCount(set));
}
private static void expectSocketSuccess(String msg, int domain, int type) {
try {
IoUtils.closeQuietly(Os.socket(domain, type, 0));
} catch (ErrnoException e) {
fail(msg + e.getMessage());
}
}
private static void expectSocketPemissionError(String msg, int domain, int type) {
try {
IoUtils.closeQuietly(Os.socket(domain, type, 0));
fail(msg);
} catch (ErrnoException e) {
assertEquals(msg, e.errno, EPERM);
}
}
private static void expectHasNetworking() {
expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
AF_UNIX, SOCK_STREAM);
expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException",
AF_INET, SOCK_DGRAM);
expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException",
AF_INET6, SOCK_DGRAM);
}
private static void expectNoNetworking() {
expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
AF_UNIX, SOCK_STREAM);
expectSocketPemissionError(
"Creating a AF_INET socket should have thrown ErrnoException(EPERM)",
AF_INET, SOCK_DGRAM);
expectSocketPemissionError(
"Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)",
AF_INET6, SOCK_DGRAM);
}
@Test
public void testSetAllowNetworkingForProcess() {
expectHasNetworking();
NetworkUtils.setAllowNetworkingForProcess(false);
expectNoNetworking();
NetworkUtils.setAllowNetworkingForProcess(true);
expectHasNetworking();
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.net;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import static android.system.OsConstants.AF_UNIX;
import static android.system.OsConstants.EPERM;
import static android.system.OsConstants.SOCK_DGRAM;
import static android.system.OsConstants.SOCK_STREAM;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.fail;
import android.system.ErrnoException;
import android.system.Os;
import androidx.test.runner.AndroidJUnit4;
import libcore.io.IoUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@androidx.test.filters.SmallTest
public class NetworkUtilsInternalTest {
private static void expectSocketSuccess(String msg, int domain, int type) {
try {
IoUtils.closeQuietly(Os.socket(domain, type, 0));
} catch (ErrnoException e) {
fail(msg + e.getMessage());
}
}
private static void expectSocketPemissionError(String msg, int domain, int type) {
try {
IoUtils.closeQuietly(Os.socket(domain, type, 0));
fail(msg);
} catch (ErrnoException e) {
assertEquals(msg, e.errno, EPERM);
}
}
private static void expectHasNetworking() {
expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
AF_UNIX, SOCK_STREAM);
expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException",
AF_INET, SOCK_DGRAM);
expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException",
AF_INET6, SOCK_DGRAM);
}
private static void expectNoNetworking() {
expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
AF_UNIX, SOCK_STREAM);
expectSocketPemissionError(
"Creating a AF_INET socket should have thrown ErrnoException(EPERM)",
AF_INET, SOCK_DGRAM);
expectSocketPemissionError(
"Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)",
AF_INET6, SOCK_DGRAM);
}
@Test
public void testSetAllowNetworkingForProcess() {
expectHasNetworking();
NetworkUtilsInternal.setAllowNetworkingForProcess(false);
expectNoNetworking();
NetworkUtilsInternal.setAllowNetworkingForProcess(true);
expectHasNetworking();
}
}

View File

@@ -23,11 +23,11 @@ import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static android.net.NetworkStatsHistory.FIELD_ALL;
import static android.net.NetworkTemplate.buildTemplateMobileAll;
import static android.net.NetworkUtils.multiplySafeByRational;
import static android.os.Process.myUid;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
import static com.android.internal.net.NetworkUtilsInternal.multiplySafeByRational;
import static com.android.testutils.MiscAsserts.assertThrows;
import static org.junit.Assert.assertArrayEquals;