blob: 8005dda3faf94aa70a24944e8bf56e1219849412 [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;
Chalard Jean08577fc2018-05-02 21:14:54 +090057import android.net.NetworkFactory;
Jeff Sharkey899223b2012-08-04 15:24:58 -070058import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040059import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070060import android.net.NetworkMisc;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090061import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070062import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040063import android.net.UidRange;
Charles Hea0a87e82017-05-15 17:07:18 +010064import android.net.VpnService;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070065import android.os.Binder;
Charles Hea0a87e82017-05-15 17:07:18 +010066import android.os.Build.VERSION_CODES;
67import android.os.Bundle;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080068import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070069import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070070import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070072import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070074import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070075import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070076import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070077import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070078import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070079import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010080import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070081import android.security.Credentials;
82import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040083import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010084import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070085import android.util.Log;
86
Tony Mak1a405fe2016-06-30 11:19:20 +010087import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070088import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010089import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040090import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070091import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070092import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080093import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050095import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060096import com.android.internal.util.ArrayUtils;
97import com.android.server.ConnectivityService;
Christopher Tatee0be7e82017-02-08 17:38:20 -080098import com.android.server.DeviceIdleController;
99import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700100import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700101
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000102import libcore.io.IoUtils;
103
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700104import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700105import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700106import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700107import java.io.OutputStream;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900108import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700109import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700110import java.net.Inet6Address;
111import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700112import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400113import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700114import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100115import java.util.Collection;
116import java.util.Collections;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900117import java.util.Comparator;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400118import java.util.List;
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900119import java.util.Objects;
Robin Lee4d03abc2016-05-09 12:32:27 +0100120import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400121import java.util.SortedSet;
122import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700123import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700124
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125/**
126 * @hide
127 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128public class Vpn {
129 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700130 private static final String TAG = "Vpn";
131 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132
Christopher Tatee0be7e82017-02-08 17:38:20 -0800133 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
134 // the device idle whitelist during service launch and VPN bootstrap.
Chalard Jeandd59ece2017-12-20 13:23:32 +0900135 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS = 60 * 1000;
Christopher Tatee0be7e82017-02-08 17:38:20 -0800136
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900137 // Settings for how much of the address space should be routed so that Vpn considers
138 // "most" of the address space is routed. This is used to determine whether this Vpn
139 // should be marked with the INTERNET capability.
140 private static final long MOST_IPV4_ADDRESSES_COUNT;
141 private static final BigInteger MOST_IPV6_ADDRESSES_COUNT;
142 static {
143 // 85% of the address space must be routed for Vpn to consider this VPN to provide
144 // INTERNET access.
145 final int howManyPercentIsMost = 85;
146
147 final long twoPower32 = 1L << 32;
148 MOST_IPV4_ADDRESSES_COUNT = twoPower32 * howManyPercentIsMost / 100;
149 final BigInteger twoPower128 = BigInteger.ONE.shiftLeft(128);
150 MOST_IPV6_ADDRESSES_COUNT = twoPower128
151 .multiply(BigInteger.valueOf(howManyPercentIsMost))
152 .divide(BigInteger.valueOf(100));
153 }
Chalard Jeane0d26f62018-03-29 14:10:44 +0900154 // How many routes to evaluate before bailing and declaring this Vpn should provide
Pavel Grafova462bcb2019-01-25 08:50:06 +0000155 // the INTERNET capability. This is necessary because computing the address space is
Chalard Jeane0d26f62018-03-29 14:10:44 +0900156 // O(n²) and this is running in the system service, so a limit is needed to alleviate
157 // the risk of attack.
158 // This is taken as a total of IPv4 + IPV6 routes for simplicity, but the algorithm
159 // is actually O(n²)+O(n²).
160 private static final int MAX_ROUTES_TO_EVALUATE = 150;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create separate trackers for each unique VPN to support
163 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700164
Chalard Jean546ec6b2018-10-01 12:58:19 +0900165 private final Context mContext;
166 private final NetworkInfo mNetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400167 private String mPackage;
168 private int mOwnerUID;
Varun Anand1215f092019-01-14 11:45:33 -0800169 private boolean mIsPackageTargetingAtLeastQ;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700170 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700171 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700172 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700173 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700174 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400175 private final INetworkManagementService mNetd;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900176 @VisibleForTesting
177 protected VpnConfig mConfig;
178 @VisibleForTesting
179 protected NetworkAgent mNetworkAgent;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400180 private final Looper mLooper;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900181 @VisibleForTesting
182 protected final NetworkCapabilities mNetworkCapabilities;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000183 private final SystemServices mSystemServices;
Chad Brubakerc2865192013-07-10 14:46:23 -0700184
Robin Lee4d03abc2016-05-09 12:32:27 +0100185 /**
Robin Lee17e61832016-05-09 13:46:28 +0100186 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
187 * only applies to {@link VpnService} connections.
188 */
189 private boolean mAlwaysOn = false;
190
191 /**
192 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
193 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
194 * not set.
195 */
196 private boolean mLockdown = false;
197
198 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +0000199 * Set of packages in addition to the VPN app itself that can access the network directly when
200 * VPN is not connected even if {@code mLockdown} is set.
201 */
202 private @NonNull List<String> mLockdownWhitelist = Collections.emptyList();
203
204 /**
Robin Lee17e61832016-05-09 13:46:28 +0100205 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
206 * when VPN is not running. For example, during system startup or after a crash.
207 * @see mLockdown
208 */
209 @GuardedBy("this")
210 private Set<UidRange> mBlockedUsers = new ArraySet<>();
211
Chalard Jeandd59ece2017-12-20 13:23:32 +0900212 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400213 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700214
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400215 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000216 @UserIdInt int userHandle) {
217 this(looper, context, netService, userHandle, new SystemServices(context));
218 }
219
220 @VisibleForTesting
221 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
222 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700223 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400224 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400225 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400226 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000227 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400228
229 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400230 mOwnerUID = getAppUid(mPackage, mUserHandle);
Varun Anand1215f092019-01-14 11:45:33 -0800231 mIsPackageTargetingAtLeastQ = doesPackageTargetAtLeastQ(mPackage);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700232
233 try {
234 netService.registerObserver(mObserver);
235 } catch (RemoteException e) {
236 Log.wtf(TAG, "Problem registering observer", e);
237 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400238
Chalard Jeandd59ece2017-12-20 13:23:32 +0900239 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
240 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400241 mNetworkCapabilities = new NetworkCapabilities();
242 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
243 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Varun Anand4fa80e82019-02-06 10:13:38 -0800244 updateCapabilities(null /* defaultNetwork */);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000245
246 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700247 }
248
Jeff Sharkey57666932013-04-30 17:01:57 -0700249 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900250 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700251 * teardown. When {@code false}, teardown is handled externally by someone
252 * else.
253 */
254 public void setEnableTeardown(boolean enableTeardown) {
255 mEnableTeardown = enableTeardown;
256 }
257
Jeff Sharkey899223b2012-08-04 15:24:58 -0700258 /**
259 * Update current state, dispaching event to listeners.
260 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100261 @VisibleForTesting
262 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700263 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
264 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400265 if (mNetworkAgent != null) {
266 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
267 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100268 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700269 }
270
Varun Anand4fa80e82019-02-06 10:13:38 -0800271 /**
272 * Updates {@link #mNetworkCapabilities} based on current underlying networks and returns a
273 * defensive copy.
274 *
275 * <p>Does not propagate updated capabilities to apps.
276 *
277 * @param defaultNetwork underlying network for VPNs following platform's default
278 */
279 public synchronized NetworkCapabilities updateCapabilities(
280 @Nullable Network defaultNetwork) {
281 if (mConfig == null) {
282 // VPN is not running.
283 return null;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600284 }
Varun Anand4fa80e82019-02-06 10:13:38 -0800285
286 Network[] underlyingNetworks = mConfig.underlyingNetworks;
287 if (underlyingNetworks == null && defaultNetwork != null) {
288 // null underlying networks means to track the default.
289 underlyingNetworks = new Network[] { defaultNetwork };
290 }
291 // Only apps targeting Q and above can explicitly declare themselves as metered.
292 final boolean isAlwaysMetered = mIsPackageTargetingAtLeastQ && mConfig.isMetered;
293
294 applyUnderlyingCapabilities(
295 mContext.getSystemService(ConnectivityManager.class),
296 underlyingNetworks,
297 mNetworkCapabilities,
298 isAlwaysMetered);
299
300 return new NetworkCapabilities(mNetworkCapabilities);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600301 }
302
303 @VisibleForTesting
Varun Anand4fa80e82019-02-06 10:13:38 -0800304 public static void applyUnderlyingCapabilities(
305 ConnectivityManager cm,
306 Network[] underlyingNetworks,
307 NetworkCapabilities caps,
308 boolean isAlwaysMetered) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600309 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
310 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
311 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Varun Anand1215f092019-01-14 11:45:33 -0800312 // VPN's meteredness is OR'd with isAlwaysMetered and meteredness of its underlying
313 // networks.
314 boolean metered = isAlwaysMetered;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600315 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900316 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600317
Chalard Jean3bd57052018-05-21 15:30:56 +0900318 boolean hadUnderlyingNetworks = false;
319 if (null != underlyingNetworks) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600320 for (Network underlying : underlyingNetworks) {
Varun Anand4fa80e82019-02-06 10:13:38 -0800321 // TODO(b/124469351): Get capabilities directly from ConnectivityService instead.
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600322 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700323 if (underlyingCaps == null) continue;
Chalard Jean3bd57052018-05-21 15:30:56 +0900324 hadUnderlyingNetworks = true;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600325 for (int underlyingType : underlyingCaps.getTransportTypes()) {
326 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
327 }
328
329 // When we have multiple networks, we have to assume the
330 // worst-case link speed and restrictions.
331 downKbps = NetworkCapabilities.minBandwidth(downKbps,
332 underlyingCaps.getLinkDownstreamBandwidthKbps());
333 upKbps = NetworkCapabilities.minBandwidth(upKbps,
334 underlyingCaps.getLinkUpstreamBandwidthKbps());
335 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
336 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900337 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600338 }
339 }
Chalard Jean3bd57052018-05-21 15:30:56 +0900340 if (!hadUnderlyingNetworks) {
341 // No idea what the underlying networks are; assume sane defaults
342 metered = true;
343 roaming = false;
344 congested = false;
345 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600346
347 caps.setTransportTypes(transportTypes);
348 caps.setLinkDownstreamBandwidthKbps(downKbps);
349 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900350 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
351 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
352 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600353 }
354
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700355 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000356 * Chooses whether to force all connections to go though VPN.
357 *
358 * Used to enable/disable legacy VPN lockdown.
359 *
Pavel Grafova462bcb2019-01-25 08:50:06 +0000360 * This uses the same ip rule mechanism as
361 * {@link #setAlwaysOnPackage(String, boolean, List<String>)}; previous settings from calling
362 * that function will be replaced and saved with the always-on state.
Robin Leec3736bc2017-03-10 16:19:54 +0000363 *
364 * @param lockdown whether to prevent all traffic outside of a VPN.
365 */
366 public synchronized void setLockdown(boolean lockdown) {
367 enforceControlPermissionOrInternalCaller();
368
369 setVpnForcedLocked(lockdown);
370 mLockdown = lockdown;
371
372 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
373 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
374 if (mAlwaysOn) {
375 saveAlwaysOnPackage();
376 }
377 }
378
379 /**
junyulai8ed89152018-10-25 10:56:17 +0800380 * Check whether to prevent all traffic outside of a VPN even when the VPN is not connected.
381 *
382 * @return {@code true} if VPN lockdown is enabled.
383 */
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000384 public synchronized boolean getLockdown() {
junyulai8ed89152018-10-25 10:56:17 +0800385 return mLockdown;
386 }
387
388 /**
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000389 * Returns whether VPN is configured as always-on.
390 */
391 public synchronized boolean getAlwaysOn() {
392 return mAlwaysOn;
393 }
394
395 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100396 * Checks if a VPN app supports always-on mode.
397 *
398 * In order to support the always-on feature, an app has to
399 * <ul>
400 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100401 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
402 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100403 * </ul>
404 *
405 * @param packageName the canonical package name of the VPN app
406 * @return {@code true} if and only if the VPN app exists and supports always-on mode
407 */
408 public boolean isAlwaysOnPackageSupported(String packageName) {
409 enforceSettingsPermission();
410
411 if (packageName == null) {
412 return false;
413 }
414
415 PackageManager pm = mContext.getPackageManager();
416 ApplicationInfo appInfo = null;
417 try {
418 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
419 } catch (NameNotFoundException unused) {
420 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
421 }
422 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
423 return false;
424 }
425
426 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
427 intent.setPackage(packageName);
428 List<ResolveInfo> services =
429 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
430 if (services == null || services.size() == 0) {
431 return false;
432 }
433
434 for (ResolveInfo rInfo : services) {
435 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100436 if (metaData != null &&
437 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100438 return false;
439 }
440 }
441
442 return true;
443 }
444
445 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000446 * Configures an always-on VPN connection through a specific application.
447 * This connection is automatically granted and persisted after a reboot.
448 *
449 * <p>The designated package should exist and declare a {@link VpnService} in its
450 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
451 * otherwise the call will fail.
452 *
Charles Hea0a87e82017-05-15 17:07:18 +0100453 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
454 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
455 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
456 *
Robin Lee17e61832016-05-09 13:46:28 +0100457 * @param packageName the package to designate as always-on VPN supplier.
458 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Pavel Grafova462bcb2019-01-25 08:50:06 +0000459 * @param lockdownWhitelist packages to be whitelisted from lockdown.
Robin Lee9ff1a582016-06-10 16:41:10 +0100460 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000461 */
Pavel Grafova462bcb2019-01-25 08:50:06 +0000462 public synchronized boolean setAlwaysOnPackage(
463 String packageName, boolean lockdown, List<String> lockdownWhitelist) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000464 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000465
Pavel Grafova462bcb2019-01-25 08:50:06 +0000466 if (setAlwaysOnPackageInternal(packageName, lockdown, lockdownWhitelist)) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000467 saveAlwaysOnPackage();
468 return true;
469 }
470 return false;
471 }
472
473 /**
474 * Configures an always-on VPN connection through a specific application, the same as
475 * {@link #setAlwaysOnPackage}.
476 *
477 * Does not perform permission checks. Does not persist any of the changes to storage.
478 *
479 * @param packageName the package to designate as always-on VPN supplier.
480 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Pavel Grafova462bcb2019-01-25 08:50:06 +0000481 * @param lockdownWhitelist packages to be whitelisted from lockdown. This is only used if
482 * {@code lockdown} is {@code true}. Packages must not contain commas.
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000483 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
484 */
485 @GuardedBy("this")
Pavel Grafova462bcb2019-01-25 08:50:06 +0000486 private boolean setAlwaysOnPackageInternal(
487 String packageName, boolean lockdown, List<String> lockdownWhitelist) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100488 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
489 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
490 return false;
491 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000492
Pavel Grafova462bcb2019-01-25 08:50:06 +0000493 if (lockdownWhitelist != null) {
494 for (String pkg : lockdownWhitelist) {
495 if (pkg.contains(",")) {
496 Log.w(TAG, "Not setting always-on vpn, invalid whitelisted package: " + pkg);
497 return false;
498 }
499 }
500 }
501
Robin Lee244ce8e2016-01-05 18:03:46 +0000502 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100503 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000504 if (!setPackageAuthorization(packageName, true)) {
505 return false;
506 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100507 mAlwaysOn = true;
508 } else {
509 packageName = VpnConfig.LEGACY_VPN;
510 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000511 }
512
Robin Lee17e61832016-05-09 13:46:28 +0100513 mLockdown = (mAlwaysOn && lockdown);
Pavel Grafova462bcb2019-01-25 08:50:06 +0000514 mLockdownWhitelist = (mLockdown && lockdownWhitelist != null)
515 ? Collections.unmodifiableList(new ArrayList<>(lockdownWhitelist))
516 : Collections.emptyList();
517
Tony Mak1a405fe2016-06-30 11:19:20 +0100518 if (isCurrentPreparedPackage(packageName)) {
519 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
Pavel Grafova462bcb2019-01-25 08:50:06 +0000520 setVpnForcedLocked(mLockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100521 } else {
522 // Prepare this app. The notification will update as a side-effect of updateState().
Pavel Grafova462bcb2019-01-25 08:50:06 +0000523 // It also calls setVpnForcedLocked().
Robin Lee9ff1a582016-06-10 16:41:10 +0100524 prepareInternal(packageName);
525 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000526 return true;
527 }
528
Robin Lee9ff1a582016-06-10 16:41:10 +0100529 private static boolean isNullOrLegacyVpn(String packageName) {
530 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
531 }
532
Robin Lee244ce8e2016-01-05 18:03:46 +0000533 /**
534 * @return the package name of the VPN controller responsible for always-on VPN,
535 * or {@code null} if none is set or always-on VPN is controlled through
536 * lockdown instead.
Robin Lee244ce8e2016-01-05 18:03:46 +0000537 */
538 public synchronized String getAlwaysOnPackage() {
539 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100540 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000541 }
542
543 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +0000544 * @return an immutable list of packages whitelisted from always-on VPN lockdown.
545 */
546 public synchronized List<String> getLockdownWhitelist() {
547 return mLockdown ? mLockdownWhitelist : null;
548 }
549
550 /**
Robin Lee812800c2016-05-13 15:38:08 +0100551 * Save the always-on package and lockdown config into Settings.Secure
552 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000553 @GuardedBy("this")
554 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100555 final long token = Binder.clearCallingIdentity();
556 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000557 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100558 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000559 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000560 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Pavel Grafova462bcb2019-01-25 08:50:06 +0000561 mSystemServices.settingsSecurePutStringForUser(
562 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST,
563 String.join(",", mLockdownWhitelist), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100564 } finally {
565 Binder.restoreCallingIdentity(token);
566 }
567 }
568
569 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000570 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100571 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000572 @GuardedBy("this")
573 private void loadAlwaysOnPackage() {
574 final long token = Binder.clearCallingIdentity();
575 try {
576 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
577 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
578 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
579 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
Pavel Grafova462bcb2019-01-25 08:50:06 +0000580 final String whitelistString = mSystemServices.settingsSecureGetStringForUser(
581 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN_WHITELIST, mUserHandle);
582 final List<String> whitelistedPackages = TextUtils.isEmpty(whitelistString)
583 ? Collections.emptyList() : Arrays.asList(whitelistString.split(","));
584 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown, whitelistedPackages);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000585 } finally {
586 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100587 }
588 }
589
590 /**
591 * @return {@code true} if the service was started, the service was already connected, or there
592 * was no always-on VPN to start. {@code false} otherwise.
593 */
594 public boolean startAlwaysOnVpn() {
595 final String alwaysOnPackage;
596 synchronized (this) {
597 alwaysOnPackage = getAlwaysOnPackage();
598 // Skip if there is no service to start.
599 if (alwaysOnPackage == null) {
600 return true;
601 }
Charles Hea0a87e82017-05-15 17:07:18 +0100602 // Remove always-on VPN if it's not supported.
603 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +0000604 setAlwaysOnPackage(null, false, null);
Charles Hea0a87e82017-05-15 17:07:18 +0100605 return false;
606 }
Robin Lee812800c2016-05-13 15:38:08 +0100607 // Skip if the service is already established. This isn't bulletproof: it's not bound
608 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
609 // which may restart the connection.
610 if (getNetworkInfo().isConnected()) {
611 return true;
612 }
613 }
614
Christopher Tatee0be7e82017-02-08 17:38:20 -0800615 // Tell the OS that background services in this app need to be allowed for
616 // a short time, so we can bootstrap the VPN service.
617 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100618 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800619 DeviceIdleController.LocalService idleController =
620 LocalServices.getService(DeviceIdleController.LocalService.class);
621 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900622 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800623
624 // Start the VPN service declared in the app's manifest.
625 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
626 serviceIntent.setPackage(alwaysOnPackage);
627 try {
628 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
629 } catch (RuntimeException e) {
630 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
631 return false;
632 }
633 } finally {
634 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100635 }
636 }
637
638 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700639 * Prepare for a VPN application. This method is designed to solve
640 * race conditions. It first compares the current prepared package
641 * with {@code oldPackage}. If they are the same, the prepared
642 * package is revoked and replaced with {@code newPackage}. If
643 * {@code oldPackage} is {@code null}, the comparison is omitted.
644 * If {@code newPackage} is the same package or {@code null}, the
645 * revocation is omitted. This method returns {@code true} if the
646 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700647 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700648 * Legacy VPN is handled specially since it is not a real package.
649 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
650 * it can be revoked by itself.
651 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900652 * Note: when we added VPN pre-consent in
653 * https://android.googlesource.com/platform/frameworks/base/+/0554260
654 * the names oldPackage and newPackage became misleading, because when
655 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100656 *
657 * Their meanings actually are:
658 *
659 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
660 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100661 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100662 * and revoke any current app VPN and re-prepare legacy vpn.
663 *
Robin Lee812800c2016-05-13 15:38:08 +0100664 * TODO: Rename the variables - or split this method into two - and end this confusion.
665 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
666 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100667 *
668 * @param oldPackage The package name of the old VPN application
669 * @param newPackage The package name of the new VPN application
670 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900671 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700672 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700673 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700674 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100675 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100676 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100677 return false;
678 }
679
Chalard Jeandd59ece2017-12-20 13:23:32 +0900680 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100681 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700682 // The package doesn't match. We return false (to obtain user consent) unless the
683 // user has already consented to that VPN package.
684 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
685 prepareInternal(oldPackage);
686 return true;
687 }
688 return false;
689 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
690 && !isVpnUserPreConsented(oldPackage)) {
691 // Currently prepared VPN is revoked, so unprepare it and return false.
692 prepareInternal(VpnConfig.LEGACY_VPN);
693 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700694 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700695 }
696
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700697 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700698 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100699 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700700 return true;
701 }
702
Robin Lee1b1bcd72016-02-12 18:11:30 +0000703 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700704 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700705
Victor Chang98a633a2016-05-27 17:30:49 +0100706 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100707 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100708 return false;
709 }
710
Jeff Davidson11008a72014-11-20 13:12:46 -0800711 prepareInternal(newPackage);
712 return true;
713 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700714
Victor Chang98a633a2016-05-27 17:30:49 +0100715 private boolean isCurrentPreparedPackage(String packageName) {
716 // We can't just check that packageName matches mPackage, because if the app was uninstalled
717 // and reinstalled it will no longer be prepared. Instead check the UID.
718 return getAppUid(packageName, mUserHandle) == mOwnerUID;
719 }
720
Jeff Davidson11008a72014-11-20 13:12:46 -0800721 /** Prepare the VPN for the given package. Does not perform permission checks. */
722 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400723 long token = Binder.clearCallingIdentity();
724 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800725 // Reset the interface.
726 if (mInterface != null) {
727 mStatusIntent = null;
728 agentDisconnect();
729 jniReset(mInterface);
730 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900731 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800732 }
733
734 // Revoke the connection or stop LegacyVpnRunner.
735 if (mConnection != null) {
736 try {
737 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
738 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
739 } catch (Exception e) {
740 // ignore
741 }
742 mContext.unbindService(mConnection);
743 mConnection = null;
744 } else if (mLegacyVpnRunner != null) {
745 mLegacyVpnRunner.exit();
746 mLegacyVpnRunner = null;
747 }
748
749 try {
750 mNetd.denyProtect(mOwnerUID);
751 } catch (Exception e) {
752 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
753 }
754
755 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
756 mPackage = newPackage;
757 mOwnerUID = getAppUid(newPackage, mUserHandle);
Varun Anand1215f092019-01-14 11:45:33 -0800758 mIsPackageTargetingAtLeastQ = doesPackageTargetAtLeastQ(newPackage);
Jeff Davidson11008a72014-11-20 13:12:46 -0800759 try {
760 mNetd.allowProtect(mOwnerUID);
761 } catch (Exception e) {
762 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
763 }
764 mConfig = null;
765
766 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000767 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400768 } finally {
769 Binder.restoreCallingIdentity(token);
770 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700771 }
772
Jeff Davidson05542602014-08-11 14:07:27 -0700773 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100774 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700775 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000776 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700777 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000778 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700779
Robin Lee3b3dd942015-05-12 18:14:58 +0100780 int uid = getAppUid(packageName, mUserHandle);
781 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
782 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000783 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700784 }
785
786 long token = Binder.clearCallingIdentity();
787 try {
788 AppOpsManager appOps =
789 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100790 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700791 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000792 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700793 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100794 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700795 } finally {
796 Binder.restoreCallingIdentity(token);
797 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000798 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700799 }
800
801 private boolean isVpnUserPreConsented(String packageName) {
802 AppOpsManager appOps =
803 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
804
805 // Verify that the caller matches the given package and has permission to activate VPNs.
806 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
807 packageName) == AppOpsManager.MODE_ALLOWED;
808 }
809
Paul Jensen0784eea2014-08-19 16:00:24 -0400810 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700811 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400812 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700813 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400814 PackageManager pm = mContext.getPackageManager();
815 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700816 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700817 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400818 } catch (NameNotFoundException e) {
819 result = -1;
820 }
821 return result;
822 }
823
Varun Anand1215f092019-01-14 11:45:33 -0800824 private boolean doesPackageTargetAtLeastQ(String packageName) {
825 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
826 return true;
827 }
828 PackageManager pm = mContext.getPackageManager();
829 try {
830 ApplicationInfo appInfo =
831 pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
832 return appInfo.targetSdkVersion >= VERSION_CODES.Q;
833 } catch (NameNotFoundException unused) {
834 Log.w(TAG, "Can't find \"" + packageName + "\"");
835 return false;
836 }
837 }
838
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400839 public NetworkInfo getNetworkInfo() {
840 return mNetworkInfo;
841 }
842
Paul Jensen31a94f42015-02-13 14:18:39 -0500843 public int getNetId() {
844 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
845 }
846
Lorenzo Colitti60446162014-09-20 00:14:31 +0900847 private LinkProperties makeLinkProperties() {
848 boolean allowIPv4 = mConfig.allowIPv4;
849 boolean allowIPv6 = mConfig.allowIPv6;
850
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400851 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900852
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400853 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700854
Lorenzo Colitti60446162014-09-20 00:14:31 +0900855 if (mConfig.addresses != null) {
856 for (LinkAddress address : mConfig.addresses) {
857 lp.addLinkAddress(address);
858 allowIPv4 |= address.getAddress() instanceof Inet4Address;
859 allowIPv6 |= address.getAddress() instanceof Inet6Address;
860 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400861 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900862
863 if (mConfig.routes != null) {
864 for (RouteInfo route : mConfig.routes) {
865 lp.addRoute(route);
866 InetAddress address = route.getDestination().getAddress();
867 allowIPv4 |= address instanceof Inet4Address;
868 allowIPv6 |= address instanceof Inet6Address;
869 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400870 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700871
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400872 if (mConfig.dnsServers != null) {
873 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700874 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
875 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900876 allowIPv4 |= address instanceof Inet4Address;
877 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400878 }
879 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700880
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000881 lp.setHttpProxy(mConfig.proxyInfo);
882
Lorenzo Colitti60446162014-09-20 00:14:31 +0900883 if (!allowIPv4) {
884 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
885 }
886 if (!allowIPv6) {
887 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
888 }
889
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400890 // Concatenate search domains into a string.
891 StringBuilder buffer = new StringBuilder();
892 if (mConfig.searchDomains != null) {
893 for (String domain : mConfig.searchDomains) {
894 buffer.append(domain).append(' ');
895 }
896 }
897 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700898
Lorenzo Colitti60446162014-09-20 00:14:31 +0900899 // TODO: Stop setting the MTU in jniCreate and set it here.
900
901 return lp;
902 }
903
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900904 /**
905 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
906 *
907 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
908 * space or to most of the IPv6 address space, where "most" is defined by the value of the
909 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
910 * by any of the routes, then it's decided that most of the space is routed.
911 * @hide
912 */
913 @VisibleForTesting
914 static boolean providesRoutesToMostDestinations(LinkProperties lp) {
Chalard Jeane0d26f62018-03-29 14:10:44 +0900915 final List<RouteInfo> routes = lp.getAllRoutes();
916 if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900917 final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
918 TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
919 TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
Chalard Jeane0d26f62018-03-29 14:10:44 +0900920 for (final RouteInfo route : routes) {
Rubin Xuc63e48d2019-02-19 16:56:47 +0000921 if (route.getType() == RouteInfo.RTN_UNREACHABLE) continue;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900922 IpPrefix destination = route.getDestination();
923 if (destination.isIPv4()) {
924 ipv4Prefixes.add(destination);
925 } else {
926 ipv6Prefixes.add(destination);
927 }
928 }
929 if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
930 return true;
931 }
932 return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
933 .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
934 }
935
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900936 /**
937 * Attempt to perform a seamless handover of VPNs by only updating LinkProperties without
938 * registering a new NetworkAgent. This is not always possible if the new VPN configuration
939 * has certain changes, in which case this method would just return {@code false}.
940 */
941 private boolean updateLinkPropertiesInPlaceIfPossible(NetworkAgent agent, VpnConfig oldConfig) {
942 // NetworkMisc cannot be updated without registering a new NetworkAgent.
943 if (oldConfig.allowBypass != mConfig.allowBypass) {
944 Log.i(TAG, "Handover not possible due to changes to allowBypass");
945 return false;
946 }
947
948 // TODO: we currently do not support seamless handover if the allowed or disallowed
949 // applications have changed. Consider diffing UID ranges and only applying the delta.
950 if (!Objects.equals(oldConfig.allowedApplications, mConfig.allowedApplications) ||
951 !Objects.equals(oldConfig.disallowedApplications, mConfig.disallowedApplications)) {
952 Log.i(TAG, "Handover not possible due to changes to whitelisted/blacklisted apps");
953 return false;
954 }
955
956 LinkProperties lp = makeLinkProperties();
957 final boolean hadInternetCapability = mNetworkCapabilities.hasCapability(
958 NetworkCapabilities.NET_CAPABILITY_INTERNET);
959 final boolean willHaveInternetCapability = providesRoutesToMostDestinations(lp);
960 if (hadInternetCapability != willHaveInternetCapability) {
961 // A seamless handover would have led to a change to INTERNET capability, which
962 // is supposed to be immutable for a given network. In this case bail out and do not
963 // perform handover.
964 Log.i(TAG, "Handover not possible due to changes to INTERNET capability");
965 return false;
966 }
967
968 agent.sendLinkProperties(lp);
969 return true;
970 }
971
Lorenzo Colitti60446162014-09-20 00:14:31 +0900972 private void agentConnect() {
973 LinkProperties lp = makeLinkProperties();
974
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900975 if (providesRoutesToMostDestinations(lp)) {
Lorenzo Colitti60446162014-09-20 00:14:31 +0900976 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
977 } else {
978 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
979 }
980
Robin Lee323f29d2016-05-04 16:38:06 +0100981 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700982
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700983 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100984 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700985
Chalard Jeanf474fc32018-01-17 15:10:05 +0900986 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900987 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
988 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400989 long token = Binder.clearCallingIdentity();
990 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900991 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900992 mNetworkInfo, mNetworkCapabilities, lp,
Chalard Jean08577fc2018-05-02 21:14:54 +0900993 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc,
994 NetworkFactory.SerialNumber.VPN) {
Jeff Davidson05542602014-08-11 14:07:27 -0700995 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400996 public void unwanted() {
997 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700998 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400999 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001000 } finally {
1001 Binder.restoreCallingIdentity(token);
1002 }
Robin Lee323f29d2016-05-04 16:38:06 +01001003 mNetworkInfo.setIsAvailable(true);
1004 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001005 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001006
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001007 private boolean canHaveRestrictedProfile(int userId) {
1008 long token = Binder.clearCallingIdentity();
1009 try {
1010 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
1011 } finally {
1012 Binder.restoreCallingIdentity(token);
1013 }
1014 }
1015
Tony Mak1a405fe2016-06-30 11:19:20 +01001016 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001017 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +01001018 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
1019 networkInfo.setIsAvailable(false);
1020 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001021 networkAgent.sendNetworkInfo(networkInfo);
1022 }
1023 }
1024
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001025 private void agentDisconnect() {
1026 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +01001027 mNetworkInfo.setIsAvailable(false);
1028 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001029 mNetworkAgent = null;
1030 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001031 }
1032
1033 /**
Varun Anand4fa80e82019-02-06 10:13:38 -08001034 * Establish a VPN network and return the file descriptor of the VPN interface. This methods
1035 * returns {@code null} if the application is revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -07001036 *
1037 * @param config The parameters to configure the network.
1038 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001039 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07001040 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001041 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -07001042 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001043 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -07001044 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001045 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -07001046 // Check to ensure consent hasn't been revoked since we were prepared.
1047 if (!isVpnUserPreConsented(mPackage)) {
1048 return null;
1049 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001050 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001051 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
1052 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001053 long token = Binder.clearCallingIdentity();
1054 try {
Chad Brubakerc2865192013-07-10 14:46:23 -07001055 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -04001056 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +01001057 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001058 throw new SecurityException("Restricted users cannot establish VPNs");
1059 }
1060
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001061 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +09001062 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001063 if (info == null) {
1064 throw new SecurityException("Cannot find " + config.user);
1065 }
1066 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
1067 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
1068 }
1069 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001070 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001071 } finally {
1072 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001073 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001074
Chad Brubaker850eb672014-03-21 21:02:47 +00001075 // Save the old config in case we need to go back.
1076 VpnConfig oldConfig = mConfig;
1077 String oldInterface = mInterface;
1078 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001079 NetworkAgent oldNetworkAgent = mNetworkAgent;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001080 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +00001081
Chia-chi Yehe9107902011-07-02 01:48:50 -07001082 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001083 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001084 try {
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001085 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001086
Chad Brubakerc2865192013-07-10 14:46:23 -07001087 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001088 StringBuilder builder = new StringBuilder();
1089 for (LinkAddress address : config.addresses) {
1090 builder.append(" " + address);
1091 }
1092 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001093 throw new IllegalArgumentException("At least one address must be specified");
1094 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001095 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001096 if (!mContext.bindServiceAsUser(intent, connection,
1097 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1098 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001099 throw new IllegalStateException("Cannot bind " + config.user);
1100 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001101
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001102 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001103 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001104
1105 // Fill more values.
1106 config.user = mPackage;
1107 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001108 config.startTime = SystemClock.elapsedRealtime();
1109 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001110
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001111 // Set up forwarding and DNS rules.
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001112 // First attempt to do a seamless handover that only changes the interface name and
1113 // parameters. If that fails, disconnect.
1114 if (oldConfig != null
1115 && updateLinkPropertiesInPlaceIfPossible(mNetworkAgent, oldConfig)) {
1116 // Keep mNetworkAgent unchanged
1117 } else {
1118 mNetworkAgent = null;
1119 updateState(DetailedState.CONNECTING, "establish");
1120 // Set up forwarding and DNS rules.
1121 agentConnect();
1122 // Remove the old tun's user forwarding rules
1123 // The new tun's user rules have already been added above so they will take over
1124 // as rules are deleted. This prevents data leakage as the rules are moved over.
1125 agentDisconnect(oldNetworkAgent);
1126 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001127
1128 if (oldConnection != null) {
1129 mContext.unbindService(oldConnection);
1130 }
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001131
Chad Brubaker850eb672014-03-21 21:02:47 +00001132 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001133 jniReset(oldInterface);
1134 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001135
1136 try {
1137 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1138 } catch (IOException e) {
1139 throw new IllegalStateException(
1140 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1141 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001142 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001143 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001144 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001145 // restore old state
1146 mConfig = oldConfig;
1147 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001148 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001149 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001150 mInterface = oldInterface;
1151 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001152 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001153 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001154 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001155 }
1156
Chad Brubakerc2865192013-07-10 14:46:23 -07001157 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001158 return mNetworkAgent != null && mInterface != null;
1159 }
1160
1161 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1162 // that a call to mutate VPN state is admissible.
Chalard Jeanf666d0a2018-05-18 21:47:45 +09001163 @VisibleForTesting
1164 protected boolean isCallerEstablishedOwnerLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001165 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001166 }
1167
Paul Jensen0784eea2014-08-19 16:00:24 -04001168 // Note: Return type guarantees results are deduped and sorted, which callers require.
1169 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
1170 SortedSet<Integer> uids = new TreeSet<Integer>();
1171 for (String app : packageNames) {
1172 int uid = getAppUid(app, userHandle);
1173 if (uid != -1) uids.add(uid);
1174 }
1175 return uids;
1176 }
1177
Robin Lee4d03abc2016-05-09 12:32:27 +01001178 /**
1179 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1180 * associated with one user, and any restricted profiles attached to that user.
1181 *
1182 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1183 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1184 * in each user and profile will be included.
1185 *
1186 * @param userHandle The userId to create UID ranges for along with any of its restricted
1187 * profiles.
1188 * @param allowedApplications (optional) whitelist of applications to include.
1189 * @param disallowedApplications (optional) blacklist of applications to exclude.
1190 */
1191 @VisibleForTesting
1192 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1193 @Nullable List<String> allowedApplications,
1194 @Nullable List<String> disallowedApplications) {
1195 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001196
Robin Lee4d03abc2016-05-09 12:32:27 +01001197 // Assign the top-level user to the set of ranges
1198 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1199
1200 // If the user can have restricted profiles, assign all its restricted profiles too
1201 if (canHaveRestrictedProfile(userHandle)) {
1202 final long token = Binder.clearCallingIdentity();
1203 List<UserInfo> users;
1204 try {
Robin Lee17e61832016-05-09 13:46:28 +01001205 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001206 } finally {
1207 Binder.restoreCallingIdentity(token);
1208 }
1209 for (UserInfo user : users) {
1210 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1211 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1212 }
1213 }
1214 }
1215 return ranges;
1216 }
1217
1218 /**
1219 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1220 * associated with one user.
1221 *
1222 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1223 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1224 * in the user will be included.
1225 *
1226 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1227 * @param userHandle The userId to add to {@param ranges}.
1228 * @param allowedApplications (optional) whitelist of applications to include.
1229 * @param disallowedApplications (optional) blacklist of applications to exclude.
1230 */
1231 @VisibleForTesting
1232 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1233 @Nullable List<String> allowedApplications,
1234 @Nullable List<String> disallowedApplications) {
1235 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001236 // Add ranges covering all UIDs for allowedApplications.
1237 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001238 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001239 if (start == -1) {
1240 start = uid;
1241 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001242 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001243 start = uid;
1244 }
1245 stop = uid;
1246 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001247 if (start != -1) ranges.add(new UidRange(start, stop));
1248 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001249 // Add all ranges for user skipping UIDs for disallowedApplications.
1250 final UidRange userRange = UidRange.createForUser(userHandle);
1251 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001252 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001253 if (uid == start) {
1254 start++;
1255 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001256 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001257 start = uid + 1;
1258 }
1259 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001260 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001261 } else {
1262 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001263 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001264 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001265 }
1266
Paul Jensen0784eea2014-08-19 16:00:24 -04001267 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1268 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001269 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1270 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1271 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001272 final UidRange userRange = UidRange.createForUser(userHandle);
1273 final List<UidRange> ranges = new ArrayList<UidRange>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001274 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001275 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001276 ranges.add(range);
1277 }
1278 }
1279 return ranges;
1280 }
1281
Varun Anand4fa80e82019-02-06 10:13:38 -08001282 /**
1283 * Updates UID ranges for this VPN and also updates its internal capabilities.
1284 *
1285 * <p>Should be called on primary ConnectivityService thread.
1286 */
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001287 public void onUserAdded(int userHandle) {
1288 // If the user is restricted tie them to the parent user's VPN
1289 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001290 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001291 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001292 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1293 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001294 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001295 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001296 mConfig.disallowedApplications);
Varun Anand4fa80e82019-02-06 10:13:38 -08001297 // ConnectivityService will call {@link #updateCapabilities} and apply
1298 // 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 add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001302 }
Robin Lee17e61832016-05-09 13:46:28 +01001303 }
Robin Leec3736bc2017-03-10 16:19:54 +00001304 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001305 }
1306 }
1307 }
1308
Varun Anand4fa80e82019-02-06 10:13:38 -08001309 /**
1310 * Updates UID ranges for this VPN and also updates its capabilities.
1311 *
1312 * <p>Should be called on primary ConnectivityService thread.
1313 */
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001314 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001315 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001316 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001317 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001318 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001319 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1320 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001321 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001322 final List<UidRange> removedRanges =
1323 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001324 existingRanges.removeAll(removedRanges);
Varun Anand4fa80e82019-02-06 10:13:38 -08001325 // ConnectivityService will call {@link #updateCapabilities} and
1326 // apply those for VPN network.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001327 mNetworkCapabilities.setUids(existingRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001328 } catch (Exception e) {
1329 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1330 }
1331 }
Robin Leec3736bc2017-03-10 16:19:54 +00001332 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001333 }
1334 }
1335 }
1336
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001337 /**
Robin Lee17e61832016-05-09 13:46:28 +01001338 * Called when the user associated with this VPN has just been stopped.
1339 */
1340 public synchronized void onUserStopped() {
1341 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001342 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001343 mAlwaysOn = false;
1344
1345 // Quit any active connections
1346 agentDisconnect();
1347 }
1348
1349 /**
Pavel Grafova462bcb2019-01-25 08:50:06 +00001350 * Restricts network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1351 * service app itself and whitelisted packages, to only sockets that have had {@code protect()}
1352 * called on them. All non-VPN traffic is blocked via a {@code PROHIBIT} response from the
1353 * kernel.
Robin Lee17e61832016-05-09 13:46:28 +01001354 *
1355 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1356 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1357 *
1358 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1359 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1360 *
1361 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1362 * {@link Vpn} goes through a VPN connection or is blocked until one is
1363 * available, {@code false} to lift the requirement.
1364 *
1365 * @see #mBlockedUsers
1366 */
1367 @GuardedBy("this")
1368 private void setVpnForcedLocked(boolean enforce) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00001369 final List<String> exemptedPackages;
1370 if (isNullOrLegacyVpn(mPackage)) {
1371 exemptedPackages = null;
1372 } else {
1373 exemptedPackages = new ArrayList<>(mLockdownWhitelist);
1374 exemptedPackages.add(mPackage);
1375 }
Robin Lee17e61832016-05-09 13:46:28 +01001376 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
Robin Leec3736bc2017-03-10 16:19:54 +00001377
1378 Set<UidRange> addedRanges = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001379 if (enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001380 addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
Robin Lee17e61832016-05-09 13:46:28 +01001381 /* allowedApplications */ null,
Robin Leec3736bc2017-03-10 16:19:54 +00001382 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001383
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001384 // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
1385 // directly from the kernel and is marked as uid=0. So we adjust the range to allow
1386 // it through (b/69873852).
1387 for (UidRange range : addedRanges) {
1388 if (range.start == 0) {
1389 addedRanges.remove(range);
1390 if (range.stop != 0) {
1391 addedRanges.add(new UidRange(1, range.stop));
1392 }
1393 }
1394 }
1395
Robin Lee17e61832016-05-09 13:46:28 +01001396 removedRanges.removeAll(addedRanges);
1397 addedRanges.removeAll(mBlockedUsers);
Robin Lee17e61832016-05-09 13:46:28 +01001398 }
Robin Leec3736bc2017-03-10 16:19:54 +00001399
1400 setAllowOnlyVpnForUids(false, removedRanges);
1401 setAllowOnlyVpnForUids(true, addedRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001402 }
1403
1404 /**
1405 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1406 * to make connections through sockets that have had {@code protect()} called on them.
1407 *
1408 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1409 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1410 * {@code true}) or to remove.
1411 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1412 * including added ranges that already existed or removed ones that didn't.
1413 */
1414 @GuardedBy("this")
1415 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1416 if (ranges.size() == 0) {
1417 return true;
1418 }
1419 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1420 try {
1421 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1422 } catch (RemoteException | RuntimeException e) {
1423 Log.e(TAG, "Updating blocked=" + enforce
1424 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1425 return false;
1426 }
1427 if (enforce) {
1428 mBlockedUsers.addAll(ranges);
1429 } else {
1430 mBlockedUsers.removeAll(ranges);
1431 }
1432 return true;
1433 }
1434
1435 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001436 * Return the configuration of the currently running VPN.
1437 */
1438 public VpnConfig getVpnConfig() {
1439 enforceControlPermission();
1440 return mConfig;
1441 }
1442
Jeff Sharkey899223b2012-08-04 15:24:58 -07001443 @Deprecated
1444 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1445 try {
1446 mObserver.interfaceStatusChanged(iface, up);
1447 } catch (RemoteException e) {
1448 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001449 }
1450 }
1451
Jeff Sharkey899223b2012-08-04 15:24:58 -07001452 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1453 @Override
1454 public void interfaceStatusChanged(String interfaze, boolean up) {
1455 synchronized (Vpn.this) {
1456 if (!up && mLegacyVpnRunner != null) {
1457 mLegacyVpnRunner.check(interfaze);
1458 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001459 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001460 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001461
Jeff Sharkey899223b2012-08-04 15:24:58 -07001462 @Override
1463 public void interfaceRemoved(String interfaze) {
1464 synchronized (Vpn.this) {
1465 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001466 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001467 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001468 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001469 mInterface = null;
1470 if (mConnection != null) {
1471 mContext.unbindService(mConnection);
1472 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001473 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001474 } else if (mLegacyVpnRunner != null) {
1475 mLegacyVpnRunner.exit();
1476 mLegacyVpnRunner = null;
1477 }
1478 }
1479 }
1480 }
1481 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001482
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001483 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001484 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001485 }
1486
Robin Lee244ce8e2016-01-05 18:03:46 +00001487 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001488 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001489 // in the system server.
1490 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1491 "Unauthorized Caller");
1492 }
1493
Charles Hea0a87e82017-05-15 17:07:18 +01001494 private void enforceSettingsPermission() {
1495 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1496 "Unauthorized Caller");
1497 }
1498
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001499 private class Connection implements ServiceConnection {
1500 private IBinder mService;
1501
1502 @Override
1503 public void onServiceConnected(ComponentName name, IBinder service) {
1504 mService = service;
1505 }
1506
1507 @Override
1508 public void onServiceDisconnected(ComponentName name) {
1509 mService = null;
1510 }
1511 }
1512
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001513 private void prepareStatusIntent() {
1514 final long token = Binder.clearCallingIdentity();
1515 try {
1516 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1517 } finally {
1518 Binder.restoreCallingIdentity(token);
1519 }
1520 }
1521
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001522 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001523 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001524 return false;
1525 }
1526 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001527 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001528 return success;
1529 }
1530
1531 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001532 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001533 return false;
1534 }
1535 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001536 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001537 return success;
1538 }
1539
Varun Anand4fa80e82019-02-06 10:13:38 -08001540 /**
1541 * Updates underlying network set.
1542 *
1543 * <p>Note: Does not updates capabilities. Call {@link #updateCapabilities} from
1544 * ConnectivityService thread to get updated capabilities.
1545 */
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001546 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1547 if (!isCallerEstablishedOwnerLocked()) {
1548 return false;
1549 }
1550 if (networks == null) {
1551 mConfig.underlyingNetworks = null;
1552 } else {
1553 mConfig.underlyingNetworks = new Network[networks.length];
1554 for (int i = 0; i < networks.length; ++i) {
1555 if (networks[i] == null) {
1556 mConfig.underlyingNetworks[i] = null;
1557 } else {
1558 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1559 }
1560 }
1561 }
1562 return true;
1563 }
1564
1565 public synchronized Network[] getUnderlyingNetworks() {
1566 if (!isRunningLocked()) {
1567 return null;
1568 }
1569 return mConfig.underlyingNetworks;
1570 }
1571
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001572 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001573 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001574 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1575 */
1576 public synchronized VpnInfo getVpnInfo() {
1577 if (!isRunningLocked()) {
1578 return null;
1579 }
1580
1581 VpnInfo info = new VpnInfo();
1582 info.ownerUid = mOwnerUID;
1583 info.vpnIface = mInterface;
1584 return info;
1585 }
1586
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001587 public synchronized boolean appliesToUid(int uid) {
1588 if (!isRunningLocked()) {
1589 return false;
1590 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001591 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001592 }
1593
Robin Lee17e61832016-05-09 13:46:28 +01001594 /**
junyulai8ed89152018-10-25 10:56:17 +08001595 * @param uid The target uid.
Robin Lee17e61832016-05-09 13:46:28 +01001596 *
junyulai8ed89152018-10-25 10:56:17 +08001597 * @return {@code true} if {@code uid} is included in one of the mBlockedUsers ranges and the
1598 * VPN is not connected, or if the VPN is connected but does not apply to the {@code uid}.
1599 *
1600 * @apiNote This method don't check VPN lockdown status.
Robin Lee17e61832016-05-09 13:46:28 +01001601 * @see #mBlockedUsers
1602 */
1603 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001604 if (mNetworkInfo.isConnected()) {
1605 return !appliesToUid(uid);
1606 } else {
1607 for (UidRange uidRange : mBlockedUsers) {
1608 if (uidRange.contains(uid)) {
1609 return true;
1610 }
1611 }
1612 return false;
1613 }
Robin Lee17e61832016-05-09 13:46:28 +01001614 }
1615
Tony Mak1a405fe2016-06-30 11:19:20 +01001616 private void updateAlwaysOnNotification(DetailedState networkState) {
1617 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001618
Tony Mak1a405fe2016-06-30 11:19:20 +01001619 final UserHandle user = UserHandle.of(mUserHandle);
1620 final long token = Binder.clearCallingIdentity();
1621 try {
1622 final NotificationManager notificationManager = NotificationManager.from(mContext);
1623 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001624 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001625 return;
1626 }
Charles Heab6f2f62017-07-12 15:30:00 +01001627 final Intent intent = new Intent();
1628 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1629 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1630 intent.putExtra("lockdown", mLockdown);
1631 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001632 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1633 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001634 final Notification.Builder builder =
1635 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1636 .setSmallIcon(R.drawable.vpn_connected)
1637 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1638 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1639 .setContentIntent(configIntent)
1640 .setCategory(Notification.CATEGORY_SYSTEM)
1641 .setVisibility(Notification.VISIBILITY_PUBLIC)
1642 .setOngoing(true)
1643 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001644 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1645 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001646 } finally {
1647 Binder.restoreCallingIdentity(token);
1648 }
1649 }
1650
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001651 /**
1652 * Facade for system service calls that change, or depend on, state outside of
1653 * {@link ConnectivityService} and have hard-to-mock interfaces.
1654 *
1655 * @see com.android.server.connectivity.VpnTest
1656 */
1657 @VisibleForTesting
1658 public static class SystemServices {
1659 private final Context mContext;
1660
1661 public SystemServices(@NonNull Context context) {
1662 mContext = context;
1663 }
1664
1665 /**
1666 * @see PendingIntent#getActivityAsUser()
1667 */
1668 public PendingIntent pendingIntentGetActivityAsUser(
1669 Intent intent, int flags, UserHandle user) {
1670 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1671 null /*options*/, user);
1672 }
1673
1674 /**
1675 * @see Settings.Secure#putStringForUser
1676 */
1677 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1678 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1679 }
1680
1681 /**
1682 * @see Settings.Secure#putIntForUser
1683 */
1684 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1685 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1686 }
1687
1688 /**
1689 * @see Settings.Secure#getStringForUser
1690 */
1691 public String settingsSecureGetStringForUser(String key, int userId) {
1692 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1693 }
1694
1695 /**
1696 * @see Settings.Secure#getIntForUser
1697 */
1698 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1699 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1700 }
1701 }
1702
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001703 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001704 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001705 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001706 private native void jniReset(String interfaze);
1707 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001708 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1709 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001710
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001711 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1712 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001713 // Currently legacy VPN only works on IPv4.
1714 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001715 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001716 }
1717 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001718
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001719 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001720 }
1721
1722 /**
1723 * Start legacy VPN, controlling native daemons as needed. Creates a
1724 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001725 *
1726 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1727 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1728 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001729 */
1730 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001731 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001732 long token = Binder.clearCallingIdentity();
1733 try {
1734 startLegacyVpnPrivileged(profile, keyStore, egress);
1735 } finally {
1736 Binder.restoreCallingIdentity(token);
1737 }
1738 }
1739
1740 /**
1741 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1742 * permissions under the assumption that the caller is the system.
1743 *
1744 * Callers are responsible for checking permissions if needed.
1745 */
1746 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1747 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001748 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001749 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001750 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1751 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001752 throw new SecurityException("Restricted users cannot establish VPNs");
1753 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001754
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001755 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1756 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1757 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001758
1759 // Load certificates.
1760 String privateKey = "";
1761 String userCert = "";
1762 String caCert = "";
1763 String serverCert = "";
1764 if (!profile.ipsecUserCert.isEmpty()) {
1765 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1766 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001767 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001768 }
1769 if (!profile.ipsecCaCert.isEmpty()) {
1770 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001771 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001772 }
1773 if (!profile.ipsecServerCert.isEmpty()) {
1774 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001775 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001776 }
1777 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1778 throw new IllegalStateException("Cannot load credentials");
1779 }
1780
1781 // Prepare arguments for racoon.
1782 String[] racoon = null;
1783 switch (profile.type) {
1784 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1785 racoon = new String[] {
1786 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1787 profile.ipsecSecret, "1701",
1788 };
1789 break;
1790 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1791 racoon = new String[] {
1792 iface, profile.server, "udprsa", privateKey, userCert,
1793 caCert, serverCert, "1701",
1794 };
1795 break;
1796 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1797 racoon = new String[] {
1798 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1799 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1800 };
1801 break;
1802 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1803 racoon = new String[] {
1804 iface, profile.server, "xauthrsa", privateKey, userCert,
1805 caCert, serverCert, profile.username, profile.password, "", gateway,
1806 };
1807 break;
1808 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1809 racoon = new String[] {
1810 iface, profile.server, "hybridrsa",
1811 caCert, serverCert, profile.username, profile.password, "", gateway,
1812 };
1813 break;
1814 }
1815
1816 // Prepare arguments for mtpd.
1817 String[] mtpd = null;
1818 switch (profile.type) {
1819 case VpnProfile.TYPE_PPTP:
1820 mtpd = new String[] {
1821 iface, "pptp", profile.server, "1723",
1822 "name", profile.username, "password", profile.password,
1823 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1824 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1825 (profile.mppe ? "+mppe" : "nomppe"),
1826 };
1827 break;
1828 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1829 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1830 mtpd = new String[] {
1831 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1832 "name", profile.username, "password", profile.password,
1833 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1834 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1835 };
1836 break;
1837 }
1838
1839 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001840 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001841 config.user = profile.key;
1842 config.interfaze = iface;
1843 config.session = profile.name;
Varun Anand1215f092019-01-14 11:45:33 -08001844 config.isMetered = false;
Takayuki, Ogura5ad260d2019-01-25 19:47:05 +09001845 config.proxyInfo = profile.proxy;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001846
1847 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001848 if (!profile.dnsServers.isEmpty()) {
1849 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1850 }
1851 if (!profile.searchDomains.isEmpty()) {
1852 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1853 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001854 startLegacyVpn(config, racoon, mtpd);
1855 }
1856
1857 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001858 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001859
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001860 // Prepare for the new request.
1861 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001862 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001863
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001864 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001865 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1866 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001867 }
1868
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001869 /** Stop legacy VPN. Permissions must be checked by callers. */
1870 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001871 if (mLegacyVpnRunner != null) {
1872 mLegacyVpnRunner.exit();
1873 mLegacyVpnRunner = null;
1874
1875 synchronized (LegacyVpnRunner.TAG) {
1876 // wait for old thread to completely finish before spinning up
1877 // new instance, otherwise state updates can be out of order.
1878 }
1879 }
1880 }
1881
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001882 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001883 * Return the information of the current ongoing legacy VPN.
1884 */
1885 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001886 // Check if the caller is authorized.
1887 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001888 return getLegacyVpnInfoPrivileged();
1889 }
1890
1891 /**
1892 * Return the information of the current ongoing legacy VPN.
1893 * Callers are responsible for checking permissions if needed.
1894 */
1895 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001896 if (mLegacyVpnRunner == null) return null;
1897
1898 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001899 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001900 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001901 if (mNetworkInfo.isConnected()) {
1902 info.intent = mStatusIntent;
1903 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001904 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001905 }
1906
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001907 public VpnConfig getLegacyVpnConfig() {
1908 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001909 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001910 } else {
1911 return null;
1912 }
1913 }
1914
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001915 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001916 * Bringing up a VPN connection takes time, and that is all this thread
1917 * does. Here we have plenty of time. The only thing we need to take
1918 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001919 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001920 * machine, but it is much easier to read in the current form.
1921 */
1922 private class LegacyVpnRunner extends Thread {
1923 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001924
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001925 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001926 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001927 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001928 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001929 private final AtomicInteger mOuterConnection =
1930 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001931
Chalard Jeandd59ece2017-12-20 13:23:32 +09001932 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001933
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001934 /**
1935 * Watch for the outer connection (passing in the constructor) going away.
1936 */
1937 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1938 @Override
1939 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001940 if (!mEnableTeardown) return;
1941
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001942 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1943 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1944 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1945 NetworkInfo info = (NetworkInfo)intent.getExtra(
1946 ConnectivityManager.EXTRA_NETWORK_INFO);
1947 if (info != null && !info.isConnectedOrConnecting()) {
1948 try {
1949 mObserver.interfaceStatusChanged(mOuterInterface, false);
1950 } catch (RemoteException e) {}
1951 }
1952 }
1953 }
1954 }
1955 };
1956
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001957 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001958 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001959 mConfig = config;
1960 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001961 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001962 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001963 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001964
1965 // This is the interface which VPN is running on,
1966 // mConfig.interfaze will change to point to OUR
1967 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001968 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001969 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001970 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001971 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001972
Paul Jensene75b9e32015-04-06 11:54:53 -04001973 if (!TextUtils.isEmpty(mOuterInterface)) {
1974 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1975 for (Network network : cm.getAllNetworks()) {
1976 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001977 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001978 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1979 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1980 }
1981 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001982 }
1983
1984 IntentFilter filter = new IntentFilter();
1985 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1986 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001987 }
1988
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001989 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001990 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001991 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1992 exit();
1993 }
1994 }
1995
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001996 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001997 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001998 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001999 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07002000 try {
2001 mContext.unregisterReceiver(mBroadcastReceiver);
2002 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002003 }
2004
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002005 @Override
2006 public void run() {
2007 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002008 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002009 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002010 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002011 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002012 bringup();
2013 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002014 interrupted(); // Clear interrupt flag if execute called exit.
2015 } catch (InterruptedException e) {
2016 } finally {
2017 for (LocalSocket socket : mSockets) {
2018 IoUtils.closeQuietly(socket);
2019 }
2020 // This sleep is necessary for racoon to successfully complete sending delete
2021 // message to server.
2022 try {
2023 Thread.sleep(50);
2024 } catch (InterruptedException e) {
2025 }
2026 for (String daemon : mDaemons) {
2027 SystemService.stop(daemon);
2028 }
2029 }
2030 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002031 }
2032 }
2033
Chalard Jeandd59ece2017-12-20 13:23:32 +09002034 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002035 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09002036 if (now - mBringupStartTime <= 60000) {
2037 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002038 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002039 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09002040 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002041 }
2042 }
2043
Chalard Jeandd59ece2017-12-20 13:23:32 +09002044 private void bringup() {
2045 // Catch all exceptions so we can clean up a few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002046 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002047 try {
2048 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09002049 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002050
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002051 // Wait for the daemons to stop.
2052 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002053 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002054 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002055 }
2056 }
2057
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002058 // Clear the previous state.
2059 File state = new File("/data/misc/vpn/state");
2060 state.delete();
2061 if (state.exists()) {
2062 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002063 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08002064 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002065 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002066
Chia-chi Yehe9107902011-07-02 01:48:50 -07002067 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002068 boolean restart = false;
2069 for (String[] arguments : mArguments) {
2070 restart = restart || (arguments != null);
2071 }
2072 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002073 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002074 return;
2075 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002076 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002077
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002078 // Start the daemon with arguments.
2079 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002080 String[] arguments = mArguments[i];
2081 if (arguments == null) {
2082 continue;
2083 }
2084
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002085 // Start the daemon.
2086 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002087 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002088
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002089 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002090 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002091 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002092 }
2093
2094 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002095 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002096 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002097 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002098
2099 // Wait for the socket to connect.
2100 while (true) {
2101 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002102 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002103 break;
2104 } catch (Exception e) {
2105 // ignore
2106 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002107 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002108 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002109 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002110
2111 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002112 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002113 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07002114 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002115 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002116 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002117 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002118 out.write(bytes.length >> 8);
2119 out.write(bytes.length);
2120 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002121 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002122 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002123 out.write(0xFF);
2124 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002125 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002126
2127 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002128 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002129 while (true) {
2130 try {
2131 if (in.read() == -1) {
2132 break;
2133 }
2134 } catch (Exception e) {
2135 // ignore
2136 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002137 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002138 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002139 }
2140
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002141 // Wait for the daemons to create the new state.
2142 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002143 // Check if a running daemon is dead.
2144 for (int i = 0; i < mDaemons.length; ++i) {
2145 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002146 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002147 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002148 }
2149 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002150 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002151 }
2152
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002153 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002154 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002155 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002156 throw new IllegalStateException("Cannot parse the state");
2157 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002158
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002159 // Set the interface and the addresses in the config.
2160 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002161
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002162 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002163 // Set the routes if they are not set in the config.
2164 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002165 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002166 }
2167
2168 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002169 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002170 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002171 if (!dnsServers.isEmpty()) {
2172 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2173 }
2174 }
2175
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002176 // Set the search domains if they are not set in the config.
2177 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2178 String searchDomains = parameters[4].trim();
2179 if (!searchDomains.isEmpty()) {
2180 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2181 }
2182 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002183
Lorenzo Colitti50262792014-09-19 01:53:35 +09002184 // Add a throw route for the VPN server endpoint, if one was specified.
2185 String endpoint = parameters[5];
2186 if (!endpoint.isEmpty()) {
2187 try {
2188 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2189 if (addr instanceof Inet4Address) {
2190 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2191 } else if (addr instanceof Inet6Address) {
2192 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2193 } else {
2194 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2195 }
2196 } catch (IllegalArgumentException e) {
2197 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2198 }
2199 }
2200
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002201 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002202 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002203 // Set the start time
2204 mConfig.startTime = SystemClock.elapsedRealtime();
2205
Chalard Jeandd59ece2017-12-20 13:23:32 +09002206 // Check if the thread was interrupted while we were waiting on the lock.
2207 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002208
Chia-chi Yehe9107902011-07-02 01:48:50 -07002209 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002210 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002211 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002212 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002213
2214 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002215 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002216 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002217
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002218 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002219
2220 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002221 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002222 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002223 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002224 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002225 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002226 }
2227 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002228
2229 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002230 * Check all daemons every two seconds. Return when one of them is stopped.
2231 * The caller will move to the disconnected state when this function returns,
2232 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002233 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002234 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002235 if (!mNetworkInfo.isConnected()) {
2236 return;
2237 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002238 while (true) {
2239 Thread.sleep(2000);
2240 for (int i = 0; i < mDaemons.length; i++) {
2241 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2242 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002243 }
2244 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002245 }
2246 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002247 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002248}