blob: 08e73efb8f826ec28724f4b1f22d53dc9b080940 [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen31a94f42015-02-13 14:18:39 -050020import static android.net.ConnectivityManager.NETID_UNSET;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +090021import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060022import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
23import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti50262792014-09-19 01:53:35 +090024import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090025import static android.net.RouteInfo.RTN_UNREACHABLE;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026
Jeff Davidsonbc19c182014-11-11 13:20:01 -080027import android.Manifest;
Robin Lee4d03abc2016-05-09 12:32:27 +010028import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.UserIdInt;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070031import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070032import android.app.AppOpsManager;
Tony Mak1a405fe2016-06-30 11:19:20 +010033import android.app.Notification;
34import android.app.NotificationManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070035import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070036import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.content.Context;
39import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070040import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041import android.content.ServiceConnection;
Charles Hea0a87e82017-05-15 17:07:18 +010042import android.content.pm.ApplicationInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040044import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070045import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070046import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070048import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090049import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070050import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070051import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070052import android.net.LocalSocket;
53import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080054import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.NetworkAgent;
56import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070059import android.net.NetworkMisc;
Lorenzo Colitti6654b082020-01-10 00:40:28 +090060import android.net.NetworkProvider;
Jeff Sharkey82f85212012-08-24 11:17:25 -070061import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040062import android.net.UidRange;
Charles Hea0a87e82017-05-15 17:07:18 +010063import android.net.VpnService;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.os.Binder;
Charles Hea0a87e82017-05-15 17:07:18 +010065import android.os.Build.VERSION_CODES;
66import android.os.Bundle;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080067import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070068import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070069import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070071import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070073import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070074import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070075import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070076import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070077import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070078import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010079import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import android.security.Credentials;
81import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040082import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010083import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.util.Log;
85
Tony Mak1a405fe2016-06-30 11:19:20 +010086import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070087import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010088import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040089import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070090import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070091import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080092import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070093import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050094import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060095import com.android.internal.util.ArrayUtils;
96import com.android.server.ConnectivityService;
Christopher Tatee0be7e82017-02-08 17:38:20 -080097import com.android.server.DeviceIdleController;
98import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -070099import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700100
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000101import libcore.io.IoUtils;
102
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700103import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700104import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700105import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700106import java.io.OutputStream;
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000107import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700109import java.net.Inet6Address;
110import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700111import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700113import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100114import java.util.Collection;
115import java.util.Collections;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400116import java.util.List;
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900117import java.util.Objects;
Robin Lee4d03abc2016-05-09 12:32:27 +0100118import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400119import java.util.SortedSet;
120import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700121import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700122
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700123/**
124 * @hide
125 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400126public class Vpn {
127 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700128 private static final String TAG = "Vpn";
129 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400130
Christopher Tatee0be7e82017-02-08 17:38:20 -0800131 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
132 // the device idle whitelist during service launch and VPN bootstrap.
Chalard Jeandd59ece2017-12-20 13:23:32 +0900133 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS = 60 * 1000;
Christopher Tatee0be7e82017-02-08 17:38:20 -0800134
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000135 // Settings for how much of the address space should be routed so that Vpn considers
136 // "most" of the address space is routed. This is used to determine whether this Vpn
137 // should be marked with the INTERNET capability.
138 private static final long MOST_IPV4_ADDRESSES_COUNT;
139 private static final BigInteger MOST_IPV6_ADDRESSES_COUNT;
140 static {
141 // 85% of the address space must be routed for Vpn to consider this VPN to provide
142 // INTERNET access.
143 final int howManyPercentIsMost = 85;
144
145 final long twoPower32 = 1L << 32;
146 MOST_IPV4_ADDRESSES_COUNT = twoPower32 * howManyPercentIsMost / 100;
147 final BigInteger twoPower128 = BigInteger.ONE.shiftLeft(128);
148 MOST_IPV6_ADDRESSES_COUNT = twoPower128
149 .multiply(BigInteger.valueOf(howManyPercentIsMost))
150 .divide(BigInteger.valueOf(100));
151 }
152 // How many routes to evaluate before bailing and declaring this Vpn should provide
153 // the INTERNET capability. This is necessary because computing the address space is
154 // O(n²) and this is running in the system service, so a limit is needed to alleviate
155 // the risk of attack.
156 // This is taken as a total of IPv4 + IPV6 routes for simplicity, but the algorithm
157 // is actually O(n²)+O(n²).
158 private static final int MAX_ROUTES_TO_EVALUATE = 150;
159
Jeff Sharkey899223b2012-08-04 15:24:58 -0700160 // TODO: create separate trackers for each unique VPN to support
161 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700162
Chalard Jean546ec6b2018-10-01 12:58:19 +0900163 private final Context mContext;
164 private final NetworkInfo mNetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400165 private String mPackage;
166 private int mOwnerUID;
Varun Anand1215f092019-01-14 11:45:33 -0800167 private boolean mIsPackageTargetingAtLeastQ;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700168 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700169 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700170 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700171 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700172 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173 private final INetworkManagementService mNetd;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900174 @VisibleForTesting
175 protected VpnConfig mConfig;
176 @VisibleForTesting
177 protected NetworkAgent mNetworkAgent;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400178 private final Looper mLooper;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900179 @VisibleForTesting
180 protected final NetworkCapabilities mNetworkCapabilities;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000181 private final SystemServices mSystemServices;
Chad Brubakerc2865192013-07-10 14:46:23 -0700182
Robin Lee4d03abc2016-05-09 12:32:27 +0100183 /**
Robin Lee17e61832016-05-09 13:46:28 +0100184 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
185 * only applies to {@link VpnService} connections.
186 */
187 private boolean mAlwaysOn = false;
188
189 /**
190 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
191 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
192 * not set.
193 */
194 private boolean mLockdown = false;
195
196 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +0000197 * Set of packages in addition to the VPN app itself that can access the network directly when
198 * VPN is not connected even if {@code mLockdown} is set.
199 */
200 private @NonNull List<String> mLockdownWhitelist = Collections.emptyList();
201
Chalard Jean85dc33f2019-09-27 20:24:34 +0900202 /**
203 * A memory of what UIDs this class told netd to block for the lockdown feature.
204 *
205 * Netd maintains ranges of UIDs for which network should be restricted to using only the VPN
206 * for the lockdown feature. This class manages these UIDs and sends this information to netd.
207 * To avoid sending the same commands multiple times (which would be wasteful) and to be able
208 * to revoke lists (when the rules should change), it's simplest to keep this cache of what
209 * netd knows, so it can be diffed and sent most efficiently.
210 *
211 * The contents of this list must only be changed when updating the UIDs lists with netd,
212 * since it needs to keep in sync with the picture netd has of them.
213 *
Robin Lee17e61832016-05-09 13:46:28 +0100214 * @see mLockdown
215 */
216 @GuardedBy("this")
Chalard Jean85dc33f2019-09-27 20:24:34 +0900217 private final Set<UidRange> mBlockedUidsAsToldToNetd = new ArraySet<>();
Robin Lee17e61832016-05-09 13:46:28 +0100218
Chalard Jeandd59ece2017-12-20 13:23:32 +0900219 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400220 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700221
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400222 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000223 @UserIdInt int userHandle) {
224 this(looper, context, netService, userHandle, new SystemServices(context));
225 }
226
227 @VisibleForTesting
228 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
229 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700230 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400231 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400232 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400233 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000234 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400235
236 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400237 mOwnerUID = getAppUid(mPackage, mUserHandle);
Varun Anand1215f092019-01-14 11:45:33 -0800238 mIsPackageTargetingAtLeastQ = doesPackageTargetAtLeastQ(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700239
240 try {
241 netService.registerObserver(mObserver);
242 } catch (RemoteException e) {
243 Log.wtf(TAG, "Problem registering observer", e);
244 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400245
Chalard Jeandd59ece2017-12-20 13:23:32 +0900246 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
247 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400248 mNetworkCapabilities = new NetworkCapabilities();
249 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
250 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Varun Anand4fa80e82019-02-06 10:13:38 -0800251 updateCapabilities(null /* defaultNetwork */);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000252
253 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700254 }
255
Jeff Sharkey57666932013-04-30 17:01:57 -0700256 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900257 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700258 * teardown. When {@code false}, teardown is handled externally by someone
259 * else.
260 */
261 public void setEnableTeardown(boolean enableTeardown) {
262 mEnableTeardown = enableTeardown;
263 }
264
Jeff Sharkey899223b2012-08-04 15:24:58 -0700265 /**
Chalard Jean85dc33f2019-09-27 20:24:34 +0900266 * Update current state, dispatching event to listeners.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700267 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100268 @VisibleForTesting
269 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700270 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
271 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400272 if (mNetworkAgent != null) {
273 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
274 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100275 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700276 }
277
Varun Anand4fa80e82019-02-06 10:13:38 -0800278 /**
279 * Updates {@link #mNetworkCapabilities} based on current underlying networks and returns a
280 * defensive copy.
281 *
282 * <p>Does not propagate updated capabilities to apps.
283 *
284 * @param defaultNetwork underlying network for VPNs following platform's default
285 */
286 public synchronized NetworkCapabilities updateCapabilities(
287 @Nullable Network defaultNetwork) {
288 if (mConfig == null) {
289 // VPN is not running.
290 return null;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600291 }
Varun Anand4fa80e82019-02-06 10:13:38 -0800292
293 Network[] underlyingNetworks = mConfig.underlyingNetworks;
294 if (underlyingNetworks == null && defaultNetwork != null) {
295 // null underlying networks means to track the default.
296 underlyingNetworks = new Network[] { defaultNetwork };
297 }
298 // Only apps targeting Q and above can explicitly declare themselves as metered.
299 final boolean isAlwaysMetered = mIsPackageTargetingAtLeastQ && mConfig.isMetered;
300
301 applyUnderlyingCapabilities(
302 mContext.getSystemService(ConnectivityManager.class),
303 underlyingNetworks,
304 mNetworkCapabilities,
305 isAlwaysMetered);
306
307 return new NetworkCapabilities(mNetworkCapabilities);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600308 }
309
310 @VisibleForTesting
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000311 public static void applyUnderlyingCapabilities(
Varun Anand4fa80e82019-02-06 10:13:38 -0800312 ConnectivityManager cm,
313 Network[] underlyingNetworks,
314 NetworkCapabilities caps,
315 boolean isAlwaysMetered) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600316 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
317 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
318 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Varun Anand1215f092019-01-14 11:45:33 -0800319 // VPN's meteredness is OR'd with isAlwaysMetered and meteredness of its underlying
320 // networks.
321 boolean metered = isAlwaysMetered;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600322 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900323 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600324
Chalard Jean3bd57052018-05-21 15:30:56 +0900325 boolean hadUnderlyingNetworks = false;
326 if (null != underlyingNetworks) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600327 for (Network underlying : underlyingNetworks) {
Varun Anand4fa80e82019-02-06 10:13:38 -0800328 // TODO(b/124469351): Get capabilities directly from ConnectivityService instead.
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600329 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700330 if (underlyingCaps == null) continue;
Chalard Jean3bd57052018-05-21 15:30:56 +0900331 hadUnderlyingNetworks = true;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600332 for (int underlyingType : underlyingCaps.getTransportTypes()) {
333 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
334 }
335
336 // When we have multiple networks, we have to assume the
337 // worst-case link speed and restrictions.
338 downKbps = NetworkCapabilities.minBandwidth(downKbps,
339 underlyingCaps.getLinkDownstreamBandwidthKbps());
340 upKbps = NetworkCapabilities.minBandwidth(upKbps,
341 underlyingCaps.getLinkUpstreamBandwidthKbps());
342 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
343 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900344 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600345 }
346 }
Chalard Jean3bd57052018-05-21 15:30:56 +0900347 if (!hadUnderlyingNetworks) {
348 // No idea what the underlying networks are; assume sane defaults
349 metered = true;
350 roaming = false;
351 congested = false;
352 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600353
354 caps.setTransportTypes(transportTypes);
355 caps.setLinkDownstreamBandwidthKbps(downKbps);
356 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900357 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
358 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
359 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600360 }
361
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700362 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000363 * Chooses whether to force all connections to go though VPN.
364 *
365 * Used to enable/disable legacy VPN lockdown.
366 *
Pavel Grafova462bcb2019-01-25 08:50:06 +0000367 * This uses the same ip rule mechanism as
368 * {@link #setAlwaysOnPackage(String, boolean, List<String>)}; previous settings from calling
369 * that function will be replaced and saved with the always-on state.
Robin Leec3736bc2017-03-10 16:19:54 +0000370 *
371 * @param lockdown whether to prevent all traffic outside of a VPN.
372 */
373 public synchronized void setLockdown(boolean lockdown) {
374 enforceControlPermissionOrInternalCaller();
375
376 setVpnForcedLocked(lockdown);
377 mLockdown = lockdown;
378
379 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
380 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
381 if (mAlwaysOn) {
382 saveAlwaysOnPackage();
383 }
384 }
385
386 /**
junyulai8ed89152018-10-25 10:56:17 +0800387 * Check whether to prevent all traffic outside of a VPN even when the VPN is not connected.
388 *
389 * @return {@code true} if VPN lockdown is enabled.
390 */
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000391 public synchronized boolean getLockdown() {
junyulai8ed89152018-10-25 10:56:17 +0800392 return mLockdown;
393 }
394
395 /**
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000396 * Returns whether VPN is configured as always-on.
397 */
398 public synchronized boolean getAlwaysOn() {
399 return mAlwaysOn;
400 }
401
402 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100403 * Checks if a VPN app supports always-on mode.
404 *
405 * In order to support the always-on feature, an app has to
406 * <ul>
407 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100408 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
409 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100410 * </ul>
411 *
412 * @param packageName the canonical package name of the VPN app
413 * @return {@code true} if and only if the VPN app exists and supports always-on mode
414 */
415 public boolean isAlwaysOnPackageSupported(String packageName) {
416 enforceSettingsPermission();
417
418 if (packageName == null) {
419 return false;
420 }
421
422 PackageManager pm = mContext.getPackageManager();
423 ApplicationInfo appInfo = null;
424 try {
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000425 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
Charles Hea0a87e82017-05-15 17:07:18 +0100426 } catch (NameNotFoundException unused) {
427 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
428 }
429 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
430 return false;
431 }
432
433 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
434 intent.setPackage(packageName);
435 List<ResolveInfo> services =
436 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
437 if (services == null || services.size() == 0) {
438 return false;
439 }
440
441 for (ResolveInfo rInfo : services) {
442 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100443 if (metaData != null &&
444 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100445 return false;
446 }
447 }
448
449 return true;
450 }
451
452 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000453 * Configures an always-on VPN connection through a specific application.
454 * This connection is automatically granted and persisted after a reboot.
455 *
456 * <p>The designated package should exist and declare a {@link VpnService} in its
457 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
458 * otherwise the call will fail.
459 *
Charles Hea0a87e82017-05-15 17:07:18 +0100460 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
461 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
462 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
463 *
Robin Lee17e61832016-05-09 13:46:28 +0100464 * @param packageName the package to designate as always-on VPN supplier.
465 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Pavel Grafova462bcb2019-01-25 08:50:06 +0000466 * @param lockdownWhitelist packages to be whitelisted from lockdown.
Robin Lee9ff1a582016-06-10 16:41:10 +0100467 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000468 */
Pavel Grafova462bcb2019-01-25 08:50:06 +0000469 public synchronized boolean setAlwaysOnPackage(
470 String packageName, boolean lockdown, List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000471 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000472
Pavel Grafova462bcb2019-01-25 08:50:06 +0000473 if (setAlwaysOnPackageInternal(packageName, lockdown, lockdownWhitelist)) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000474 saveAlwaysOnPackage();
475 return true;
476 }
477 return false;
478 }
479
480 /**
481 * Configures an always-on VPN connection through a specific application, the same as
482 * {@link #setAlwaysOnPackage}.
483 *
484 * Does not perform permission checks. Does not persist any of the changes to storage.
485 *
486 * @param packageName the package to designate as always-on VPN supplier.
487 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Pavel Grafova462bcb2019-01-25 08:50:06 +0000488 * @param lockdownWhitelist packages to be whitelisted from lockdown. This is only used if
489 * {@code lockdown} is {@code true}. Packages must not contain commas.
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000490 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
491 */
492 @GuardedBy("this")
Pavel Grafova462bcb2019-01-25 08:50:06 +0000493 private boolean setAlwaysOnPackageInternal(
494 String packageName, boolean lockdown, List<String> lockdownWhitelist) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100495 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
496 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
497 return false;
498 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000499
Pavel Grafova462bcb2019-01-25 08:50:06 +0000500 if (lockdownWhitelist != null) {
501 for (String pkg : lockdownWhitelist) {
502 if (pkg.contains(",")) {
503 Log.w(TAG, "Not setting always-on vpn, invalid whitelisted package: " + pkg);
504 return false;
505 }
506 }
507 }
508
Robin Lee244ce8e2016-01-05 18:03:46 +0000509 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100510 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000511 if (!setPackageAuthorization(packageName, true)) {
512 return false;
513 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100514 mAlwaysOn = true;
515 } else {
516 packageName = VpnConfig.LEGACY_VPN;
517 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000518 }
519
Robin Lee17e61832016-05-09 13:46:28 +0100520 mLockdown = (mAlwaysOn && lockdown);
Pavel Grafova462bcb2019-01-25 08:50:06 +0000521 mLockdownWhitelist = (mLockdown && lockdownWhitelist != null)
522 ? Collections.unmodifiableList(new ArrayList<>(lockdownWhitelist))
523 : Collections.emptyList();
524
Tony Mak1a405fe2016-06-30 11:19:20 +0100525 if (isCurrentPreparedPackage(packageName)) {
526 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
Pavel Grafova462bcb2019-01-25 08:50:06 +0000527 setVpnForcedLocked(mLockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100528 } else {
529 // Prepare this app. The notification will update as a side-effect of updateState().
Pavel Grafova462bcb2019-01-25 08:50:06 +0000530 // It also calls setVpnForcedLocked().
Robin Lee9ff1a582016-06-10 16:41:10 +0100531 prepareInternal(packageName);
532 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000533 return true;
534 }
535
Robin Lee9ff1a582016-06-10 16:41:10 +0100536 private static boolean isNullOrLegacyVpn(String packageName) {
537 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
538 }
539
Robin Lee244ce8e2016-01-05 18:03:46 +0000540 /**
541 * @return the package name of the VPN controller responsible for always-on VPN,
542 * or {@code null} if none is set or always-on VPN is controlled through
543 * lockdown instead.
Robin Lee244ce8e2016-01-05 18:03:46 +0000544 */
545 public synchronized String getAlwaysOnPackage() {
546 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100547 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000548 }
549
550 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +0000551 * @return an immutable list of packages whitelisted from always-on VPN lockdown.
552 */
553 public synchronized List<String> getLockdownWhitelist() {
554 return mLockdown ? mLockdownWhitelist : null;
555 }
556
557 /**
Robin Lee812800c2016-05-13 15:38:08 +0100558 * Save the always-on package and lockdown config into Settings.Secure
559 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000560 @GuardedBy("this")
561 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100562 final long token = Binder.clearCallingIdentity();
563 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000564 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100565 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000566 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000567 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Pavel Grafova462bcb2019-01-25 08:50:06 +0000568 mSystemServices.settingsSecurePutStringForUser(
569 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST,
570 String.join(",", mLockdownWhitelist), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100571 } finally {
572 Binder.restoreCallingIdentity(token);
573 }
574 }
575
576 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000577 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100578 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000579 @GuardedBy("this")
580 private void loadAlwaysOnPackage() {
581 final long token = Binder.clearCallingIdentity();
582 try {
583 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
584 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
585 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000586 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
Pavel Grafova462bcb2019-01-25 08:50:06 +0000587 final String whitelistString = mSystemServices.settingsSecureGetStringForUser(
588 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST, mUserHandle);
589 final List<String> whitelistedPackages = TextUtils.isEmpty(whitelistString)
590 ? Collections.emptyList() : Arrays.asList(whitelistString.split(","));
591 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown, whitelistedPackages);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000592 } finally {
593 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100594 }
595 }
596
597 /**
598 * @return {@code true} if the service was started, the service was already connected, or there
599 * was no always-on VPN to start. {@code false} otherwise.
600 */
601 public boolean startAlwaysOnVpn() {
602 final String alwaysOnPackage;
603 synchronized (this) {
604 alwaysOnPackage = getAlwaysOnPackage();
605 // Skip if there is no service to start.
606 if (alwaysOnPackage == null) {
607 return true;
608 }
Charles Hea0a87e82017-05-15 17:07:18 +0100609 // Remove always-on VPN if it's not supported.
610 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +0000611 setAlwaysOnPackage(null, false, null);
Charles Hea0a87e82017-05-15 17:07:18 +0100612 return false;
613 }
Robin Lee812800c2016-05-13 15:38:08 +0100614 // Skip if the service is already established. This isn't bulletproof: it's not bound
615 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
616 // which may restart the connection.
617 if (getNetworkInfo().isConnected()) {
618 return true;
619 }
620 }
621
Christopher Tatee0be7e82017-02-08 17:38:20 -0800622 // Tell the OS that background services in this app need to be allowed for
623 // a short time, so we can bootstrap the VPN service.
624 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100625 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800626 DeviceIdleController.LocalService idleController =
627 LocalServices.getService(DeviceIdleController.LocalService.class);
628 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900629 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800630
631 // Start the VPN service declared in the app's manifest.
632 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
633 serviceIntent.setPackage(alwaysOnPackage);
634 try {
635 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
636 } catch (RuntimeException e) {
637 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
638 return false;
639 }
640 } finally {
641 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100642 }
643 }
644
645 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700646 * Prepare for a VPN application. This method is designed to solve
647 * race conditions. It first compares the current prepared package
648 * with {@code oldPackage}. If they are the same, the prepared
649 * package is revoked and replaced with {@code newPackage}. If
650 * {@code oldPackage} is {@code null}, the comparison is omitted.
651 * If {@code newPackage} is the same package or {@code null}, the
652 * revocation is omitted. This method returns {@code true} if the
653 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700654 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700655 * Legacy VPN is handled specially since it is not a real package.
656 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
657 * it can be revoked by itself.
658 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900659 * Note: when we added VPN pre-consent in
660 * https://android.googlesource.com/platform/frameworks/base/+/0554260
661 * the names oldPackage and newPackage became misleading, because when
662 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100663 *
664 * Their meanings actually are:
665 *
666 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
667 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100668 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100669 * and revoke any current app VPN and re-prepare legacy vpn.
670 *
Robin Lee812800c2016-05-13 15:38:08 +0100671 * TODO: Rename the variables - or split this method into two - and end this confusion.
672 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
673 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100674 *
675 * @param oldPackage The package name of the old VPN application
676 * @param newPackage The package name of the new VPN application
677 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900678 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700679 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700680 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700681 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100682 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100683 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100684 return false;
685 }
686
Chalard Jeandd59ece2017-12-20 13:23:32 +0900687 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100688 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700689 // The package doesn't match. We return false (to obtain user consent) unless the
690 // user has already consented to that VPN package.
691 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
692 prepareInternal(oldPackage);
693 return true;
694 }
695 return false;
696 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
697 && !isVpnUserPreConsented(oldPackage)) {
698 // Currently prepared VPN is revoked, so unprepare it and return false.
699 prepareInternal(VpnConfig.LEGACY_VPN);
700 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700701 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700702 }
703
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700704 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700705 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100706 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700707 return true;
708 }
709
Robin Lee1b1bcd72016-02-12 18:11:30 +0000710 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700711 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700712
Victor Chang98a633a2016-05-27 17:30:49 +0100713 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100714 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100715 return false;
716 }
717
Jeff Davidson11008a72014-11-20 13:12:46 -0800718 prepareInternal(newPackage);
719 return true;
720 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700721
Victor Chang98a633a2016-05-27 17:30:49 +0100722 private boolean isCurrentPreparedPackage(String packageName) {
723 // We can't just check that packageName matches mPackage, because if the app was uninstalled
724 // and reinstalled it will no longer be prepared. Instead check the UID.
725 return getAppUid(packageName, mUserHandle) == mOwnerUID;
726 }
727
Jeff Davidson11008a72014-11-20 13:12:46 -0800728 /** Prepare the VPN for the given package. Does not perform permission checks. */
729 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400730 long token = Binder.clearCallingIdentity();
731 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800732 // Reset the interface.
733 if (mInterface != null) {
734 mStatusIntent = null;
735 agentDisconnect();
736 jniReset(mInterface);
737 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900738 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800739 }
740
741 // Revoke the connection or stop LegacyVpnRunner.
742 if (mConnection != null) {
743 try {
744 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
745 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
746 } catch (Exception e) {
747 // ignore
748 }
749 mContext.unbindService(mConnection);
750 mConnection = null;
751 } else if (mLegacyVpnRunner != null) {
752 mLegacyVpnRunner.exit();
753 mLegacyVpnRunner = null;
754 }
755
756 try {
757 mNetd.denyProtect(mOwnerUID);
758 } catch (Exception e) {
759 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
760 }
761
762 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
763 mPackage = newPackage;
764 mOwnerUID = getAppUid(newPackage, mUserHandle);
Varun Anand1215f092019-01-14 11:45:33 -0800765 mIsPackageTargetingAtLeastQ = doesPackageTargetAtLeastQ(newPackage);
Jeff Davidson11008a72014-11-20 13:12:46 -0800766 try {
767 mNetd.allowProtect(mOwnerUID);
768 } catch (Exception e) {
769 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
770 }
771 mConfig = null;
772
773 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000774 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400775 } finally {
776 Binder.restoreCallingIdentity(token);
777 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700778 }
779
Jeff Davidson05542602014-08-11 14:07:27 -0700780 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100781 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700782 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000783 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700784 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000785 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700786
Robin Lee3b3dd942015-05-12 18:14:58 +0100787 int uid = getAppUid(packageName, mUserHandle);
788 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
789 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000790 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700791 }
792
793 long token = Binder.clearCallingIdentity();
794 try {
795 AppOpsManager appOps =
796 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100797 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700798 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000799 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700800 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100801 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700802 } finally {
803 Binder.restoreCallingIdentity(token);
804 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000805 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700806 }
807
808 private boolean isVpnUserPreConsented(String packageName) {
809 AppOpsManager appOps =
810 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
811
812 // Verify that the caller matches the given package and has permission to activate VPNs.
813 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
814 packageName) == AppOpsManager.MODE_ALLOWED;
815 }
816
Paul Jensen0784eea2014-08-19 16:00:24 -0400817 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700818 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400819 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700820 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400821 PackageManager pm = mContext.getPackageManager();
822 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700823 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700824 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400825 } catch (NameNotFoundException e) {
826 result = -1;
827 }
828 return result;
829 }
830
Varun Anand1215f092019-01-14 11:45:33 -0800831 private boolean doesPackageTargetAtLeastQ(String packageName) {
832 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
833 return true;
834 }
835 PackageManager pm = mContext.getPackageManager();
836 try {
837 ApplicationInfo appInfo =
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000838 pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
Varun Anand1215f092019-01-14 11:45:33 -0800839 return appInfo.targetSdkVersion >= VERSION_CODES.Q;
840 } catch (NameNotFoundException unused) {
841 Log.w(TAG, "Can't find \"" + packageName + "\"");
842 return false;
843 }
844 }
845
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400846 public NetworkInfo getNetworkInfo() {
847 return mNetworkInfo;
848 }
849
Paul Jensen31a94f42015-02-13 14:18:39 -0500850 public int getNetId() {
Chalard Jeanfe35bf92019-12-13 19:47:12 +0900851 return mNetworkAgent != null ? mNetworkAgent.network.netId : NETID_UNSET;
Paul Jensen31a94f42015-02-13 14:18:39 -0500852 }
853
Lorenzo Colitti60446162014-09-20 00:14:31 +0900854 private LinkProperties makeLinkProperties() {
855 boolean allowIPv4 = mConfig.allowIPv4;
856 boolean allowIPv6 = mConfig.allowIPv6;
857
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400858 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900859
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400860 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700861
Lorenzo Colitti60446162014-09-20 00:14:31 +0900862 if (mConfig.addresses != null) {
863 for (LinkAddress address : mConfig.addresses) {
864 lp.addLinkAddress(address);
865 allowIPv4 |= address.getAddress() instanceof Inet4Address;
866 allowIPv6 |= address.getAddress() instanceof Inet6Address;
867 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400868 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900869
870 if (mConfig.routes != null) {
871 for (RouteInfo route : mConfig.routes) {
872 lp.addRoute(route);
873 InetAddress address = route.getDestination().getAddress();
874 allowIPv4 |= address instanceof Inet4Address;
875 allowIPv6 |= address instanceof Inet6Address;
876 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400877 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700878
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400879 if (mConfig.dnsServers != null) {
880 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700881 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
882 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900883 allowIPv4 |= address instanceof Inet4Address;
884 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400885 }
886 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700887
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000888 lp.setHttpProxy(mConfig.proxyInfo);
889
Lorenzo Colitti60446162014-09-20 00:14:31 +0900890 if (!allowIPv4) {
891 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
892 }
893 if (!allowIPv6) {
894 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
895 }
896
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400897 // Concatenate search domains into a string.
898 StringBuilder buffer = new StringBuilder();
899 if (mConfig.searchDomains != null) {
900 for (String domain : mConfig.searchDomains) {
901 buffer.append(domain).append(' ');
902 }
903 }
904 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700905
Lorenzo Colitti60446162014-09-20 00:14:31 +0900906 // TODO: Stop setting the MTU in jniCreate and set it here.
907
908 return lp;
909 }
910
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900911 /**
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900912 * Attempt to perform a seamless handover of VPNs by only updating LinkProperties without
913 * registering a new NetworkAgent. This is not always possible if the new VPN configuration
914 * has certain changes, in which case this method would just return {@code false}.
915 */
916 private boolean updateLinkPropertiesInPlaceIfPossible(NetworkAgent agent, VpnConfig oldConfig) {
917 // NetworkMisc cannot be updated without registering a new NetworkAgent.
918 if (oldConfig.allowBypass != mConfig.allowBypass) {
919 Log.i(TAG, "Handover not possible due to changes to allowBypass");
920 return false;
921 }
922
923 // TODO: we currently do not support seamless handover if the allowed or disallowed
924 // applications have changed. Consider diffing UID ranges and only applying the delta.
925 if (!Objects.equals(oldConfig.allowedApplications, mConfig.allowedApplications) ||
926 !Objects.equals(oldConfig.disallowedApplications, mConfig.disallowedApplications)) {
927 Log.i(TAG, "Handover not possible due to changes to whitelisted/blacklisted apps");
928 return false;
929 }
930
Chalard Jean06d81d22019-05-30 15:40:11 +0900931 agent.sendLinkProperties(makeLinkProperties());
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900932 return true;
933 }
934
Lorenzo Colitti60446162014-09-20 00:14:31 +0900935 private void agentConnect() {
936 LinkProperties lp = makeLinkProperties();
937
Chalard Jean06d81d22019-05-30 15:40:11 +0900938 // VPN either provide a default route (IPv4 or IPv6 or both), or they are a split tunnel
939 // that falls back to the default network, which by definition provides INTERNET (unless
940 // there is no default network, in which case none of this matters in any sense).
Chalard Jean8a0f0552019-05-30 18:06:59 +0900941 // Also, always setting the INTERNET bit guarantees that when a VPN applies to an app,
942 // the VPN will always be reported as the network by getDefaultNetwork and callbacks
943 // registered with registerDefaultNetworkCallback. This in turn protects the invariant
944 // that an app calling ConnectivityManager#bindProcessToNetwork(getDefaultNetwork())
945 // behaves the same as when it uses the default network.
Chalard Jean06d81d22019-05-30 15:40:11 +0900946 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900947
Robin Lee323f29d2016-05-04 16:38:06 +0100948 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700949
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700950 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100951 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700952
Chalard Jeanf474fc32018-01-17 15:10:05 +0900953 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900954 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
955 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400956 long token = Binder.clearCallingIdentity();
957 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900958 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900959 mNetworkInfo, mNetworkCapabilities, lp,
Chalard Jean05ab6812018-05-02 21:14:54 +0900960 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc,
Lorenzo Colitti6654b082020-01-10 00:40:28 +0900961 NetworkProvider.ID_VPN) {
Jeff Davidson05542602014-08-11 14:07:27 -0700962 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400963 public void unwanted() {
964 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700965 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400966 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700967 } finally {
968 Binder.restoreCallingIdentity(token);
969 }
Robin Lee323f29d2016-05-04 16:38:06 +0100970 mNetworkInfo.setIsAvailable(true);
971 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400972 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700973
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700974 private boolean canHaveRestrictedProfile(int userId) {
975 long token = Binder.clearCallingIdentity();
976 try {
977 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
978 } finally {
979 Binder.restoreCallingIdentity(token);
980 }
981 }
982
Tony Mak1a405fe2016-06-30 11:19:20 +0100983 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400984 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100985 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
986 networkInfo.setIsAvailable(false);
987 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400988 networkAgent.sendNetworkInfo(networkInfo);
989 }
990 }
991
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400992 private void agentDisconnect() {
993 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100994 mNetworkInfo.setIsAvailable(false);
995 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400996 mNetworkAgent = null;
997 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700998 }
999
1000 /**
Varun Anand4fa80e82019-02-06 10:13:38 -08001001 * Establish a VPN network and return the file descriptor of the VPN interface. This methods
1002 * returns {@code null} if the application is revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -07001003 *
1004 * @param config The parameters to configure the network.
1005 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001006 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07001007 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001008 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -07001009 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001010 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -07001011 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001012 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -07001013 // Check to ensure consent hasn't been revoked since we were prepared.
1014 if (!isVpnUserPreConsented(mPackage)) {
1015 return null;
1016 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001017 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001018 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
1019 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001020 long token = Binder.clearCallingIdentity();
1021 try {
Chad Brubakerc2865192013-07-10 14:46:23 -07001022 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -04001023 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +01001024 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001025 throw new SecurityException("Restricted users cannot establish VPNs");
1026 }
1027
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001028 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +09001029 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001030 if (info == null) {
1031 throw new SecurityException("Cannot find " + config.user);
1032 }
1033 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
1034 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
1035 }
1036 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001037 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001038 } finally {
1039 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001040 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001041
Chad Brubaker850eb672014-03-21 21:02:47 +00001042 // Save the old config in case we need to go back.
1043 VpnConfig oldConfig = mConfig;
1044 String oldInterface = mInterface;
1045 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001046 NetworkAgent oldNetworkAgent = mNetworkAgent;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001047 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +00001048
Chia-chi Yehe9107902011-07-02 01:48:50 -07001049 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001050 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001051 try {
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001052 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001053
Chad Brubakerc2865192013-07-10 14:46:23 -07001054 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001055 StringBuilder builder = new StringBuilder();
1056 for (LinkAddress address : config.addresses) {
Chalard Jeana9276c32019-08-27 15:21:15 +09001057 builder.append(" ");
1058 builder.append(address);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001059 }
1060 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001061 throw new IllegalArgumentException("At least one address must be specified");
1062 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001063 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001064 if (!mContext.bindServiceAsUser(intent, connection,
1065 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1066 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001067 throw new IllegalStateException("Cannot bind " + config.user);
1068 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001069
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001070 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001071 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001072
1073 // Fill more values.
1074 config.user = mPackage;
1075 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001076 config.startTime = SystemClock.elapsedRealtime();
1077 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001078
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001079 // Set up forwarding and DNS rules.
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001080 // First attempt to do a seamless handover that only changes the interface name and
1081 // parameters. If that fails, disconnect.
1082 if (oldConfig != null
1083 && updateLinkPropertiesInPlaceIfPossible(mNetworkAgent, oldConfig)) {
1084 // Keep mNetworkAgent unchanged
1085 } else {
1086 mNetworkAgent = null;
1087 updateState(DetailedState.CONNECTING, "establish");
1088 // Set up forwarding and DNS rules.
1089 agentConnect();
1090 // Remove the old tun's user forwarding rules
1091 // The new tun's user rules have already been added above so they will take over
1092 // as rules are deleted. This prevents data leakage as the rules are moved over.
1093 agentDisconnect(oldNetworkAgent);
1094 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001095
1096 if (oldConnection != null) {
1097 mContext.unbindService(oldConnection);
1098 }
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001099
Chad Brubaker850eb672014-03-21 21:02:47 +00001100 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001101 jniReset(oldInterface);
1102 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001103
1104 try {
1105 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1106 } catch (IOException e) {
1107 throw new IllegalStateException(
1108 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1109 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001110 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001111 IoUtils.closeQuietly(tun);
Rubin Xu307c5252018-06-21 17:52:55 +01001112 // If this is not seamless handover, disconnect partially-established network when error
1113 // occurs.
1114 if (oldNetworkAgent != mNetworkAgent) {
1115 agentDisconnect();
1116 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001117 // restore old state
1118 mConfig = oldConfig;
1119 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001120 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001121 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001122 mInterface = oldInterface;
1123 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001124 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001125 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001126 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001127 }
1128
Chad Brubakerc2865192013-07-10 14:46:23 -07001129 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001130 return mNetworkAgent != null && mInterface != null;
1131 }
1132
1133 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1134 // that a call to mutate VPN state is admissible.
Chalard Jeanf666d0a2018-05-18 21:47:45 +09001135 @VisibleForTesting
1136 protected boolean isCallerEstablishedOwnerLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001137 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001138 }
1139
Paul Jensen0784eea2014-08-19 16:00:24 -04001140 // Note: Return type guarantees results are deduped and sorted, which callers require.
1141 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
Chalard Jeana9276c32019-08-27 15:21:15 +09001142 SortedSet<Integer> uids = new TreeSet<>();
Paul Jensen0784eea2014-08-19 16:00:24 -04001143 for (String app : packageNames) {
1144 int uid = getAppUid(app, userHandle);
1145 if (uid != -1) uids.add(uid);
1146 }
1147 return uids;
1148 }
1149
Robin Lee4d03abc2016-05-09 12:32:27 +01001150 /**
1151 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1152 * associated with one user, and any restricted profiles attached to that user.
1153 *
1154 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1155 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1156 * in each user and profile will be included.
1157 *
1158 * @param userHandle The userId to create UID ranges for along with any of its restricted
1159 * profiles.
1160 * @param allowedApplications (optional) whitelist of applications to include.
1161 * @param disallowedApplications (optional) blacklist of applications to exclude.
1162 */
1163 @VisibleForTesting
1164 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1165 @Nullable List<String> allowedApplications,
1166 @Nullable List<String> disallowedApplications) {
1167 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001168
Robin Lee4d03abc2016-05-09 12:32:27 +01001169 // Assign the top-level user to the set of ranges
1170 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1171
1172 // If the user can have restricted profiles, assign all its restricted profiles too
1173 if (canHaveRestrictedProfile(userHandle)) {
1174 final long token = Binder.clearCallingIdentity();
1175 List<UserInfo> users;
1176 try {
Robin Lee17e61832016-05-09 13:46:28 +01001177 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001178 } finally {
1179 Binder.restoreCallingIdentity(token);
1180 }
1181 for (UserInfo user : users) {
1182 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1183 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1184 }
1185 }
1186 }
1187 return ranges;
1188 }
1189
1190 /**
1191 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1192 * associated with one user.
1193 *
1194 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1195 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1196 * in the user will be included.
1197 *
1198 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1199 * @param userHandle The userId to add to {@param ranges}.
1200 * @param allowedApplications (optional) whitelist of applications to include.
1201 * @param disallowedApplications (optional) blacklist of applications to exclude.
1202 */
1203 @VisibleForTesting
1204 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1205 @Nullable List<String> allowedApplications,
1206 @Nullable List<String> disallowedApplications) {
1207 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001208 // Add ranges covering all UIDs for allowedApplications.
1209 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001210 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001211 if (start == -1) {
1212 start = uid;
1213 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001214 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001215 start = uid;
1216 }
1217 stop = uid;
1218 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001219 if (start != -1) ranges.add(new UidRange(start, stop));
1220 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001221 // Add all ranges for user skipping UIDs for disallowedApplications.
1222 final UidRange userRange = UidRange.createForUser(userHandle);
1223 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001224 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001225 if (uid == start) {
1226 start++;
1227 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001228 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001229 start = uid + 1;
1230 }
1231 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001232 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001233 } else {
1234 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001235 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001236 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001237 }
1238
Paul Jensen0784eea2014-08-19 16:00:24 -04001239 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1240 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001241 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1242 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1243 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001244 final UidRange userRange = UidRange.createForUser(userHandle);
Chalard Jeana9276c32019-08-27 15:21:15 +09001245 final List<UidRange> ranges = new ArrayList<>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001246 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001247 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001248 ranges.add(range);
1249 }
1250 }
1251 return ranges;
1252 }
1253
Varun Anand4fa80e82019-02-06 10:13:38 -08001254 /**
1255 * Updates UID ranges for this VPN and also updates its internal capabilities.
1256 *
1257 * <p>Should be called on primary ConnectivityService thread.
1258 */
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001259 public void onUserAdded(int userHandle) {
1260 // If the user is restricted tie them to the parent user's VPN
1261 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001262 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001263 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001264 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1265 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001266 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001267 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001268 mConfig.disallowedApplications);
Varun Anand4fa80e82019-02-06 10:13:38 -08001269 // ConnectivityService will call {@link #updateCapabilities} and apply
1270 // those for VPN network.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001271 mNetworkCapabilities.setUids(existingRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001272 } catch (Exception e) {
1273 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001274 }
Robin Lee17e61832016-05-09 13:46:28 +01001275 }
Robin Leec3736bc2017-03-10 16:19:54 +00001276 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001277 }
1278 }
1279 }
1280
Varun Anand4fa80e82019-02-06 10:13:38 -08001281 /**
1282 * Updates UID ranges for this VPN and also updates its capabilities.
1283 *
1284 * <p>Should be called on primary ConnectivityService thread.
1285 */
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001286 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001287 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001288 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001289 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001290 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001291 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1292 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001293 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001294 final List<UidRange> removedRanges =
1295 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001296 existingRanges.removeAll(removedRanges);
Varun Anand4fa80e82019-02-06 10:13:38 -08001297 // ConnectivityService will call {@link #updateCapabilities} and
1298 // apply those for VPN network.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001299 mNetworkCapabilities.setUids(existingRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001300 } catch (Exception e) {
1301 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1302 }
1303 }
Robin Leec3736bc2017-03-10 16:19:54 +00001304 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001305 }
1306 }
1307 }
1308
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001309 /**
Robin Lee17e61832016-05-09 13:46:28 +01001310 * Called when the user associated with this VPN has just been stopped.
1311 */
1312 public synchronized void onUserStopped() {
1313 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001314 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001315 mAlwaysOn = false;
1316
1317 // Quit any active connections
1318 agentDisconnect();
1319 }
1320
1321 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001322 * Restricts network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1323 * service app itself and whitelisted packages, to only sockets that have had {@code protect()}
1324 * called on them. All non-VPN traffic is blocked via a {@code PROHIBIT} response from the
1325 * kernel.
Robin Lee17e61832016-05-09 13:46:28 +01001326 *
1327 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1328 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1329 *
1330 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1331 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1332 *
1333 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1334 * {@link Vpn} goes through a VPN connection or is blocked until one is
1335 * available, {@code false} to lift the requirement.
1336 *
Chalard Jean85dc33f2019-09-27 20:24:34 +09001337 * @see #mBlockedUidsAsToldToNetd
Robin Lee17e61832016-05-09 13:46:28 +01001338 */
1339 @GuardedBy("this")
1340 private void setVpnForcedLocked(boolean enforce) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001341 final List<String> exemptedPackages;
1342 if (isNullOrLegacyVpn(mPackage)) {
1343 exemptedPackages = null;
1344 } else {
1345 exemptedPackages = new ArrayList<>(mLockdownWhitelist);
1346 exemptedPackages.add(mPackage);
1347 }
Chalard Jean85dc33f2019-09-27 20:24:34 +09001348 final Set<UidRange> rangesToTellNetdToRemove = new ArraySet<>(mBlockedUidsAsToldToNetd);
Robin Leec3736bc2017-03-10 16:19:54 +00001349
Chalard Jean85dc33f2019-09-27 20:24:34 +09001350 final Set<UidRange> rangesToTellNetdToAdd;
Robin Lee17e61832016-05-09 13:46:28 +01001351 if (enforce) {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001352 final Set<UidRange> rangesThatShouldBeBlocked =
1353 createUserAndRestrictedProfilesRanges(mUserHandle,
1354 /* allowedApplications */ null,
1355 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001356
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001357 // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
1358 // directly from the kernel and is marked as uid=0. So we adjust the range to allow
1359 // it through (b/69873852).
Chalard Jean85dc33f2019-09-27 20:24:34 +09001360 for (UidRange range : rangesThatShouldBeBlocked) {
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001361 if (range.start == 0) {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001362 rangesThatShouldBeBlocked.remove(range);
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001363 if (range.stop != 0) {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001364 rangesThatShouldBeBlocked.add(new UidRange(1, range.stop));
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001365 }
1366 }
1367 }
1368
Chalard Jean85dc33f2019-09-27 20:24:34 +09001369 rangesToTellNetdToRemove.removeAll(rangesThatShouldBeBlocked);
1370 rangesToTellNetdToAdd = rangesThatShouldBeBlocked;
1371 // The ranges to tell netd to add are the ones that should be blocked minus the
1372 // ones it already knows to block. Note that this will change the contents of
1373 // rangesThatShouldBeBlocked, but the list of ranges that should be blocked is
1374 // not used after this so it's fine to destroy it.
1375 rangesToTellNetdToAdd.removeAll(mBlockedUidsAsToldToNetd);
1376 } else {
1377 rangesToTellNetdToAdd = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001378 }
Robin Leec3736bc2017-03-10 16:19:54 +00001379
Chalard Jean85dc33f2019-09-27 20:24:34 +09001380 // If mBlockedUidsAsToldToNetd used to be empty, this will always be a no-op.
1381 setAllowOnlyVpnForUids(false, rangesToTellNetdToRemove);
1382 // If nothing should be blocked now, this will now be a no-op.
1383 setAllowOnlyVpnForUids(true, rangesToTellNetdToAdd);
Robin Lee17e61832016-05-09 13:46:28 +01001384 }
1385
1386 /**
Chalard Jean85dc33f2019-09-27 20:24:34 +09001387 * Tell netd to add or remove a list of {@link UidRange}s to the list of UIDs that are only
1388 * allowed to make connections through sockets that have had {@code protect()} called on them.
Robin Lee17e61832016-05-09 13:46:28 +01001389 *
1390 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1391 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1392 * {@code true}) or to remove.
1393 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1394 * including added ranges that already existed or removed ones that didn't.
1395 */
1396 @GuardedBy("this")
1397 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1398 if (ranges.size() == 0) {
1399 return true;
1400 }
1401 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1402 try {
1403 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1404 } catch (RemoteException | RuntimeException e) {
1405 Log.e(TAG, "Updating blocked=" + enforce
1406 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1407 return false;
1408 }
1409 if (enforce) {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001410 mBlockedUidsAsToldToNetd.addAll(ranges);
Robin Lee17e61832016-05-09 13:46:28 +01001411 } else {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001412 mBlockedUidsAsToldToNetd.removeAll(ranges);
Robin Lee17e61832016-05-09 13:46:28 +01001413 }
1414 return true;
1415 }
1416
1417 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001418 * Return the configuration of the currently running VPN.
1419 */
1420 public VpnConfig getVpnConfig() {
1421 enforceControlPermission();
1422 return mConfig;
1423 }
1424
Jeff Sharkey899223b2012-08-04 15:24:58 -07001425 @Deprecated
1426 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1427 try {
1428 mObserver.interfaceStatusChanged(iface, up);
1429 } catch (RemoteException e) {
1430 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001431 }
1432 }
1433
Jeff Sharkey899223b2012-08-04 15:24:58 -07001434 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1435 @Override
1436 public void interfaceStatusChanged(String interfaze, boolean up) {
1437 synchronized (Vpn.this) {
1438 if (!up && mLegacyVpnRunner != null) {
1439 mLegacyVpnRunner.check(interfaze);
1440 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001441 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001442 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001443
Jeff Sharkey899223b2012-08-04 15:24:58 -07001444 @Override
1445 public void interfaceRemoved(String interfaze) {
1446 synchronized (Vpn.this) {
1447 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001448 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001449 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001450 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001451 mInterface = null;
1452 if (mConnection != null) {
1453 mContext.unbindService(mConnection);
1454 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001455 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001456 } else if (mLegacyVpnRunner != null) {
1457 mLegacyVpnRunner.exit();
1458 mLegacyVpnRunner = null;
1459 }
1460 }
1461 }
1462 }
1463 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001464
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001465 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001466 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001467 }
1468
Robin Lee244ce8e2016-01-05 18:03:46 +00001469 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001470 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001471 // in the system server.
1472 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1473 "Unauthorized Caller");
1474 }
1475
Charles Hea0a87e82017-05-15 17:07:18 +01001476 private void enforceSettingsPermission() {
1477 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1478 "Unauthorized Caller");
1479 }
1480
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001481 private class Connection implements ServiceConnection {
1482 private IBinder mService;
1483
1484 @Override
1485 public void onServiceConnected(ComponentName name, IBinder service) {
1486 mService = service;
1487 }
1488
1489 @Override
1490 public void onServiceDisconnected(ComponentName name) {
1491 mService = null;
1492 }
1493 }
1494
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001495 private void prepareStatusIntent() {
1496 final long token = Binder.clearCallingIdentity();
1497 try {
1498 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1499 } finally {
1500 Binder.restoreCallingIdentity(token);
1501 }
1502 }
1503
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001504 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001505 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001506 return false;
1507 }
1508 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001509 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001510 return success;
1511 }
1512
1513 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001514 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001515 return false;
1516 }
1517 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001518 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001519 return success;
1520 }
1521
Varun Anand4fa80e82019-02-06 10:13:38 -08001522 /**
1523 * Updates underlying network set.
1524 *
1525 * <p>Note: Does not updates capabilities. Call {@link #updateCapabilities} from
1526 * ConnectivityService thread to get updated capabilities.
1527 */
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001528 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1529 if (!isCallerEstablishedOwnerLocked()) {
1530 return false;
1531 }
1532 if (networks == null) {
1533 mConfig.underlyingNetworks = null;
1534 } else {
1535 mConfig.underlyingNetworks = new Network[networks.length];
1536 for (int i = 0; i < networks.length; ++i) {
1537 if (networks[i] == null) {
1538 mConfig.underlyingNetworks[i] = null;
1539 } else {
1540 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1541 }
1542 }
1543 }
1544 return true;
1545 }
1546
1547 public synchronized Network[] getUnderlyingNetworks() {
1548 if (!isRunningLocked()) {
1549 return null;
1550 }
1551 return mConfig.underlyingNetworks;
1552 }
1553
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001554 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001555 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001556 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1557 */
1558 public synchronized VpnInfo getVpnInfo() {
1559 if (!isRunningLocked()) {
1560 return null;
1561 }
1562
1563 VpnInfo info = new VpnInfo();
1564 info.ownerUid = mOwnerUID;
1565 info.vpnIface = mInterface;
1566 return info;
1567 }
1568
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001569 public synchronized boolean appliesToUid(int uid) {
1570 if (!isRunningLocked()) {
1571 return false;
1572 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001573 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001574 }
1575
Robin Lee17e61832016-05-09 13:46:28 +01001576 /**
junyulai8ed89152018-10-25 10:56:17 +08001577 * @param uid The target uid.
Robin Lee17e61832016-05-09 13:46:28 +01001578 *
Chalard Jean85dc33f2019-09-27 20:24:34 +09001579 * @return {@code true} if {@code uid} is included in one of the mBlockedUidsAsToldToNetd
1580 * ranges and the VPN is not connected, or if the VPN is connected but does not apply to
1581 * the {@code uid}.
junyulai8ed89152018-10-25 10:56:17 +08001582 *
1583 * @apiNote This method don't check VPN lockdown status.
Chalard Jean85dc33f2019-09-27 20:24:34 +09001584 * @see #mBlockedUidsAsToldToNetd
Robin Lee17e61832016-05-09 13:46:28 +01001585 */
1586 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001587 if (mNetworkInfo.isConnected()) {
1588 return !appliesToUid(uid);
1589 } else {
Chalard Jean85dc33f2019-09-27 20:24:34 +09001590 return UidRange.containsUid(mBlockedUidsAsToldToNetd, uid);
Robin Leeebbcb542016-05-24 16:35:10 +01001591 }
Robin Lee17e61832016-05-09 13:46:28 +01001592 }
1593
Tony Mak1a405fe2016-06-30 11:19:20 +01001594 private void updateAlwaysOnNotification(DetailedState networkState) {
1595 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001596
Tony Mak1a405fe2016-06-30 11:19:20 +01001597 final UserHandle user = UserHandle.of(mUserHandle);
1598 final long token = Binder.clearCallingIdentity();
1599 try {
1600 final NotificationManager notificationManager = NotificationManager.from(mContext);
1601 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001602 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001603 return;
1604 }
Charles Heab6f2f62017-07-12 15:30:00 +01001605 final Intent intent = new Intent();
1606 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1607 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1608 intent.putExtra("lockdown", mLockdown);
1609 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001610 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1611 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001612 final Notification.Builder builder =
1613 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1614 .setSmallIcon(R.drawable.vpn_connected)
1615 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1616 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1617 .setContentIntent(configIntent)
1618 .setCategory(Notification.CATEGORY_SYSTEM)
1619 .setVisibility(Notification.VISIBILITY_PUBLIC)
1620 .setOngoing(true)
1621 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001622 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1623 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001624 } finally {
1625 Binder.restoreCallingIdentity(token);
1626 }
1627 }
1628
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001629 /**
1630 * Facade for system service calls that change, or depend on, state outside of
1631 * {@link ConnectivityService} and have hard-to-mock interfaces.
1632 *
1633 * @see com.android.server.connectivity.VpnTest
1634 */
1635 @VisibleForTesting
1636 public static class SystemServices {
1637 private final Context mContext;
1638
1639 public SystemServices(@NonNull Context context) {
1640 mContext = context;
1641 }
1642
1643 /**
1644 * @see PendingIntent#getActivityAsUser()
1645 */
1646 public PendingIntent pendingIntentGetActivityAsUser(
1647 Intent intent, int flags, UserHandle user) {
Fedor Kudasove5cb0a22019-07-09 09:23:25 +00001648 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1649 null /*options*/, user);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001650 }
1651
1652 /**
1653 * @see Settings.Secure#putStringForUser
1654 */
1655 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1656 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1657 }
1658
1659 /**
1660 * @see Settings.Secure#putIntForUser
1661 */
1662 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1663 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1664 }
1665
1666 /**
1667 * @see Settings.Secure#getStringForUser
1668 */
1669 public String settingsSecureGetStringForUser(String key, int userId) {
1670 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1671 }
1672
1673 /**
1674 * @see Settings.Secure#getIntForUser
1675 */
1676 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1677 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1678 }
1679 }
1680
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001681 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001682 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001683 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001684 private native void jniReset(String interfaze);
1685 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001686 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1687 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001688
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001689 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1690 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001691 // Currently legacy VPN only works on IPv4.
1692 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001693 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001694 }
1695 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001696
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001697 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001698 }
1699
1700 /**
1701 * Start legacy VPN, controlling native daemons as needed. Creates a
1702 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001703 *
1704 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1705 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1706 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001707 */
1708 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001709 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001710 long token = Binder.clearCallingIdentity();
1711 try {
1712 startLegacyVpnPrivileged(profile, keyStore, egress);
1713 } finally {
1714 Binder.restoreCallingIdentity(token);
1715 }
1716 }
1717
1718 /**
1719 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1720 * permissions under the assumption that the caller is the system.
1721 *
1722 * Callers are responsible for checking permissions if needed.
1723 */
1724 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1725 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001726 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001727 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001728 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1729 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001730 throw new SecurityException("Restricted users cannot establish VPNs");
1731 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001732
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001733 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1734 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1735 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001736
1737 // Load certificates.
1738 String privateKey = "";
1739 String userCert = "";
1740 String caCert = "";
1741 String serverCert = "";
1742 if (!profile.ipsecUserCert.isEmpty()) {
1743 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1744 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001745 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001746 }
1747 if (!profile.ipsecCaCert.isEmpty()) {
1748 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001749 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001750 }
1751 if (!profile.ipsecServerCert.isEmpty()) {
1752 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001753 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001754 }
Chalard Jeana9276c32019-08-27 15:21:15 +09001755 if (userCert == null || caCert == null || serverCert == null) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001756 throw new IllegalStateException("Cannot load credentials");
1757 }
1758
1759 // Prepare arguments for racoon.
1760 String[] racoon = null;
1761 switch (profile.type) {
1762 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1763 racoon = new String[] {
1764 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1765 profile.ipsecSecret, "1701",
1766 };
1767 break;
1768 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1769 racoon = new String[] {
1770 iface, profile.server, "udprsa", privateKey, userCert,
1771 caCert, serverCert, "1701",
1772 };
1773 break;
1774 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1775 racoon = new String[] {
1776 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1777 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1778 };
1779 break;
1780 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1781 racoon = new String[] {
1782 iface, profile.server, "xauthrsa", privateKey, userCert,
1783 caCert, serverCert, profile.username, profile.password, "", gateway,
1784 };
1785 break;
1786 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1787 racoon = new String[] {
1788 iface, profile.server, "hybridrsa",
1789 caCert, serverCert, profile.username, profile.password, "", gateway,
1790 };
1791 break;
1792 }
1793
1794 // Prepare arguments for mtpd.
1795 String[] mtpd = null;
1796 switch (profile.type) {
1797 case VpnProfile.TYPE_PPTP:
1798 mtpd = new String[] {
1799 iface, "pptp", profile.server, "1723",
1800 "name", profile.username, "password", profile.password,
1801 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1802 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1803 (profile.mppe ? "+mppe" : "nomppe"),
1804 };
1805 break;
1806 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1807 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1808 mtpd = new String[] {
1809 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1810 "name", profile.username, "password", profile.password,
1811 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1812 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1813 };
1814 break;
1815 }
1816
1817 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001818 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001819 config.user = profile.key;
1820 config.interfaze = iface;
1821 config.session = profile.name;
Varun Anand1215f092019-01-14 11:45:33 -08001822 config.isMetered = false;
Takayuki, Ogura5ad260d2019-01-25 19:47:05 +09001823 config.proxyInfo = profile.proxy;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001824
1825 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001826 if (!profile.dnsServers.isEmpty()) {
1827 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1828 }
1829 if (!profile.searchDomains.isEmpty()) {
1830 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1831 }
Chenbo Fengb38065d2019-05-16 16:00:01 -07001832 startLegacyVpn(config, racoon, mtpd, profile);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001833 }
1834
Chenbo Fengb38065d2019-05-16 16:00:01 -07001835 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd,
1836 VpnProfile profile) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001837 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001838
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001839 // Prepare for the new request.
1840 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001841 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001842
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001843 // Start a new LegacyVpnRunner and we are done!
Chenbo Fengb38065d2019-05-16 16:00:01 -07001844 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd, profile);
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001845 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001846 }
1847
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001848 /** Stop legacy VPN. Permissions must be checked by callers. */
1849 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001850 if (mLegacyVpnRunner != null) {
1851 mLegacyVpnRunner.exit();
1852 mLegacyVpnRunner = null;
1853
1854 synchronized (LegacyVpnRunner.TAG) {
1855 // wait for old thread to completely finish before spinning up
1856 // new instance, otherwise state updates can be out of order.
1857 }
1858 }
1859 }
1860
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001861 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001862 * Return the information of the current ongoing legacy VPN.
1863 */
1864 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001865 // Check if the caller is authorized.
1866 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001867 return getLegacyVpnInfoPrivileged();
1868 }
1869
1870 /**
1871 * Return the information of the current ongoing legacy VPN.
1872 * Callers are responsible for checking permissions if needed.
1873 */
Chalard Jeana9276c32019-08-27 15:21:15 +09001874 private synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001875 if (mLegacyVpnRunner == null) return null;
1876
1877 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001878 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001879 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001880 if (mNetworkInfo.isConnected()) {
1881 info.intent = mStatusIntent;
1882 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001883 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001884 }
1885
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001886 public VpnConfig getLegacyVpnConfig() {
1887 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001888 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001889 } else {
1890 return null;
1891 }
1892 }
1893
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001894 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001895 * Bringing up a VPN connection takes time, and that is all this thread
1896 * does. Here we have plenty of time. The only thing we need to take
1897 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001898 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001899 * machine, but it is much easier to read in the current form.
1900 */
1901 private class LegacyVpnRunner extends Thread {
1902 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001903
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001904 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001905 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001906 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001907 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001908 private final AtomicInteger mOuterConnection =
1909 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chenbo Fengb38065d2019-05-16 16:00:01 -07001910 private final VpnProfile mProfile;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001911
Chalard Jeandd59ece2017-12-20 13:23:32 +09001912 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001913
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001914 /**
1915 * Watch for the outer connection (passing in the constructor) going away.
1916 */
1917 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1918 @Override
1919 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001920 if (!mEnableTeardown) return;
1921
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001922 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1923 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1924 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1925 NetworkInfo info = (NetworkInfo)intent.getExtra(
1926 ConnectivityManager.EXTRA_NETWORK_INFO);
1927 if (info != null && !info.isConnectedOrConnecting()) {
1928 try {
1929 mObserver.interfaceStatusChanged(mOuterInterface, false);
1930 } catch (RemoteException e) {}
1931 }
1932 }
1933 }
1934 }
1935 };
1936
Chenbo Fengb38065d2019-05-16 16:00:01 -07001937 LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd, VpnProfile profile) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001938 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001939 mConfig = config;
1940 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001941 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001942 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001943 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001944
1945 // This is the interface which VPN is running on,
1946 // mConfig.interfaze will change to point to OUR
1947 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001948 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001949 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001950 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001951 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001952
Chenbo Fengb38065d2019-05-16 16:00:01 -07001953 mProfile = profile;
1954
Paul Jensene75b9e32015-04-06 11:54:53 -04001955 if (!TextUtils.isEmpty(mOuterInterface)) {
1956 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1957 for (Network network : cm.getAllNetworks()) {
1958 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001959 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001960 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1961 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1962 }
1963 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001964 }
1965
1966 IntentFilter filter = new IntentFilter();
1967 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1968 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001969 }
1970
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001971 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001972 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001973 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1974 exit();
1975 }
1976 }
1977
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001978 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001979 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001980 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001981 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001982 try {
1983 mContext.unregisterReceiver(mBroadcastReceiver);
1984 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001985 }
1986
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001987 @Override
1988 public void run() {
1989 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001990 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001991 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001992 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001993 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001994 bringup();
1995 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001996 interrupted(); // Clear interrupt flag if execute called exit.
1997 } catch (InterruptedException e) {
1998 } finally {
1999 for (LocalSocket socket : mSockets) {
2000 IoUtils.closeQuietly(socket);
2001 }
2002 // This sleep is necessary for racoon to successfully complete sending delete
2003 // message to server.
2004 try {
2005 Thread.sleep(50);
2006 } catch (InterruptedException e) {
2007 }
2008 for (String daemon : mDaemons) {
2009 SystemService.stop(daemon);
2010 }
2011 }
2012 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002013 }
2014 }
2015
Chalard Jeandd59ece2017-12-20 13:23:32 +09002016 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002017 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09002018 if (now - mBringupStartTime <= 60000) {
2019 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002020 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002021 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09002022 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002023 }
2024 }
2025
Chalard Jeandd59ece2017-12-20 13:23:32 +09002026 private void bringup() {
2027 // Catch all exceptions so we can clean up a few things.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002028 try {
2029 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09002030 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002031
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002032 // Wait for the daemons to stop.
2033 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002034 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002035 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002036 }
2037 }
2038
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002039 // Clear the previous state.
2040 File state = new File("/data/misc/vpn/state");
2041 state.delete();
2042 if (state.exists()) {
2043 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002044 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08002045 new File("/data/misc/vpn/abort").delete();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002046
Chia-chi Yehe9107902011-07-02 01:48:50 -07002047 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002048 boolean restart = false;
2049 for (String[] arguments : mArguments) {
2050 restart = restart || (arguments != null);
2051 }
2052 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002053 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002054 return;
2055 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002056 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002057
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002058 // Start the daemon with arguments.
2059 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002060 String[] arguments = mArguments[i];
2061 if (arguments == null) {
2062 continue;
2063 }
2064
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002065 // Start the daemon.
2066 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002067 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002068
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002069 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002070 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002071 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002072 }
2073
2074 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002075 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002076 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002077 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002078
2079 // Wait for the socket to connect.
2080 while (true) {
2081 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002082 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002083 break;
2084 } catch (Exception e) {
2085 // ignore
2086 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002087 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002088 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002089 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002090
2091 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002092 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002093 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07002094 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002095 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002096 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002097 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002098 out.write(bytes.length >> 8);
2099 out.write(bytes.length);
2100 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002101 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002102 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002103 out.write(0xFF);
2104 out.write(0xFF);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002105
2106 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002107 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002108 while (true) {
2109 try {
2110 if (in.read() == -1) {
2111 break;
2112 }
2113 } catch (Exception e) {
2114 // ignore
2115 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002116 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002117 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002118 }
2119
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002120 // Wait for the daemons to create the new state.
2121 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002122 // Check if a running daemon is dead.
2123 for (int i = 0; i < mDaemons.length; ++i) {
2124 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002125 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002126 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002127 }
2128 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002129 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002130 }
2131
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002132 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002133 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002134 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002135 throw new IllegalStateException("Cannot parse the state");
2136 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002137
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002138 // Set the interface and the addresses in the config.
2139 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002140
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002141 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002142 // Set the routes if they are not set in the config.
2143 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002144 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002145 }
2146
2147 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002148 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002149 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002150 if (!dnsServers.isEmpty()) {
2151 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2152 }
2153 }
2154
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002155 // Set the search domains if they are not set in the config.
2156 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2157 String searchDomains = parameters[4].trim();
2158 if (!searchDomains.isEmpty()) {
2159 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2160 }
2161 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002162
Lorenzo Colitti50262792014-09-19 01:53:35 +09002163 // Add a throw route for the VPN server endpoint, if one was specified.
Chenbo Fengb38065d2019-05-16 16:00:01 -07002164 String endpoint = parameters[5].isEmpty() ? mProfile.server : parameters[5];
Lorenzo Colitti50262792014-09-19 01:53:35 +09002165 if (!endpoint.isEmpty()) {
2166 try {
2167 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2168 if (addr instanceof Inet4Address) {
2169 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2170 } else if (addr instanceof Inet6Address) {
2171 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2172 } else {
2173 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2174 }
2175 } catch (IllegalArgumentException e) {
2176 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2177 }
2178 }
2179
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002180 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002181 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002182 // Set the start time
2183 mConfig.startTime = SystemClock.elapsedRealtime();
2184
Chalard Jeandd59ece2017-12-20 13:23:32 +09002185 // Check if the thread was interrupted while we were waiting on the lock.
2186 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002187
Chia-chi Yehe9107902011-07-02 01:48:50 -07002188 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002189 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002190 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002191 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002192
2193 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002194 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002195 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002196
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002197 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002198
2199 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002200 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002201 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002202 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002203 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002204 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002205 }
2206 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002207
2208 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002209 * Check all daemons every two seconds. Return when one of them is stopped.
2210 * The caller will move to the disconnected state when this function returns,
2211 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002212 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002213 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002214 if (!mNetworkInfo.isConnected()) {
2215 return;
2216 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002217 while (true) {
2218 Thread.sleep(2000);
2219 for (int i = 0; i < mDaemons.length; i++) {
2220 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2221 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002222 }
2223 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002224 }
2225 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002226 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002227}