blob: b7ed2f9bd473034975f8d11827d52d75d6d49859 [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen31a94f42015-02-13 14:18:39 -050020import static android.net.ConnectivityManager.NETID_UNSET;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +090021import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060022import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
23import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti50262792014-09-19 01:53:35 +090024import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090025import static android.net.RouteInfo.RTN_UNREACHABLE;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026
Jeff Davidsonbc19c182014-11-11 13:20:01 -080027import android.Manifest;
Robin Lee4d03abc2016-05-09 12:32:27 +010028import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.UserIdInt;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070031import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070032import android.app.AppOpsManager;
Tony Mak1a405fe2016-06-30 11:19:20 +010033import android.app.Notification;
34import android.app.NotificationManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070035import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070036import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.content.Context;
39import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070040import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041import android.content.ServiceConnection;
Charles Hea0a87e82017-05-15 17:07:18 +010042import android.content.pm.ApplicationInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040044import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070045import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070046import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070048import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090049import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070050import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070051import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070052import android.net.LocalSocket;
53import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080054import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.NetworkAgent;
56import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070059import android.net.NetworkMisc;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090060import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070061import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040062import android.net.UidRange;
Robin Lee812800c2016-05-13 15:38:08 +010063import android.net.Uri;
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;
Robin Lee812800c2016-05-13 15:38:08 +010074import android.os.PatternMatcher;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070075import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070076import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070077import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070078import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070079import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070080import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010081import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070082import android.security.Credentials;
83import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040084import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010085import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.util.Log;
87
Tony Mak1a405fe2016-06-30 11:19:20 +010088import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070089import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010090import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040091import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070092import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070093import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080094import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050096import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060097import com.android.internal.util.ArrayUtils;
98import com.android.server.ConnectivityService;
Christopher Tatee0be7e82017-02-08 17:38:20 -080099import com.android.server.DeviceIdleController;
100import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700102
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700103import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700104import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700105import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700106import java.io.OutputStream;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900107import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700109import java.net.Inet6Address;
110import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700111import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700113import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100114import java.util.Collection;
115import java.util.Collections;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900116import java.util.Comparator;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117import java.util.List;
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900118import java.util.Objects;
Robin Lee4d03abc2016-05-09 12:32:27 +0100119import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400120import java.util.SortedSet;
121import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700122import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700123
Bernie Innocenti00000fe2018-05-28 22:04:37 +0900124import libcore.io.IoUtils;
125
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700126/**
127 * @hide
128 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129public class Vpn {
130 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700131 private static final String TAG = "Vpn";
132 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400133
Christopher Tatee0be7e82017-02-08 17:38:20 -0800134 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
135 // the device idle whitelist during service launch and VPN bootstrap.
Chalard Jeandd59ece2017-12-20 13:23:32 +0900136 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS = 60 * 1000;
Christopher Tatee0be7e82017-02-08 17:38:20 -0800137
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900138 // Settings for how much of the address space should be routed so that Vpn considers
139 // "most" of the address space is routed. This is used to determine whether this Vpn
140 // should be marked with the INTERNET capability.
141 private static final long MOST_IPV4_ADDRESSES_COUNT;
142 private static final BigInteger MOST_IPV6_ADDRESSES_COUNT;
143 static {
144 // 85% of the address space must be routed for Vpn to consider this VPN to provide
145 // INTERNET access.
146 final int howManyPercentIsMost = 85;
147
148 final long twoPower32 = 1L << 32;
149 MOST_IPV4_ADDRESSES_COUNT = twoPower32 * howManyPercentIsMost / 100;
150 final BigInteger twoPower128 = BigInteger.ONE.shiftLeft(128);
151 MOST_IPV6_ADDRESSES_COUNT = twoPower128
152 .multiply(BigInteger.valueOf(howManyPercentIsMost))
153 .divide(BigInteger.valueOf(100));
154 }
Chalard Jeane0d26f62018-03-29 14:10:44 +0900155 // How many routes to evaluate before bailing and declaring this Vpn should provide
156 // the INTERNET capability. This is necessary because computing the adress space is
157 // O(n²) and this is running in the system service, so a limit is needed to alleviate
158 // the risk of attack.
159 // This is taken as a total of IPv4 + IPV6 routes for simplicity, but the algorithm
160 // is actually O(n²)+O(n²).
161 private static final int MAX_ROUTES_TO_EVALUATE = 150;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900162
Jeff Sharkey899223b2012-08-04 15:24:58 -0700163 // TODO: create separate trackers for each unique VPN to support
164 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700165
Chalard Jean546ec6b2018-10-01 12:58:19 +0900166 private final Context mContext;
167 private final NetworkInfo mNetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400168 private String mPackage;
169 private int mOwnerUID;
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 /**
Robin Lee17e61832016-05-09 13:46:28 +0100199 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
200 * when VPN is not running. For example, during system startup or after a crash.
201 * @see mLockdown
202 */
203 @GuardedBy("this")
204 private Set<UidRange> mBlockedUsers = new ArraySet<>();
205
Chalard Jeandd59ece2017-12-20 13:23:32 +0900206 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400207 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700208
Chalard Jeandd59ece2017-12-20 13:23:32 +0900209 // Listen to package removal and change events (update/uninstall) for this user
Robin Lee812800c2016-05-13 15:38:08 +0100210 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
211 @Override
212 public void onReceive(Context context, Intent intent) {
213 final Uri data = intent.getData();
214 final String packageName = data == null ? null : data.getSchemeSpecificPart();
215 if (packageName == null) {
216 return;
217 }
218
219 synchronized (Vpn.this) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900220 // Avoid race where always-on package has been unset
Robin Lee812800c2016-05-13 15:38:08 +0100221 if (!packageName.equals(getAlwaysOnPackage())) {
222 return;
223 }
224
225 final String action = intent.getAction();
Chalard Jeandd59ece2017-12-20 13:23:32 +0900226 Log.i(TAG, "Received broadcast " + action + " for always-on VPN package "
227 + packageName + " in user " + mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100228
229 switch(action) {
230 case Intent.ACTION_PACKAGE_REPLACED:
231 // Start vpn after app upgrade
232 startAlwaysOnVpn();
233 break;
234 case Intent.ACTION_PACKAGE_REMOVED:
235 final boolean isPackageRemoved = !intent.getBooleanExtra(
236 Intent.EXTRA_REPLACING, false);
237 if (isPackageRemoved) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000238 setAlwaysOnPackage(null, false);
Robin Lee812800c2016-05-13 15:38:08 +0100239 }
240 break;
241 }
242 }
243 }
244 };
245
246 private boolean mIsPackageIntentReceiverRegistered = false;
247
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400248 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000249 @UserIdInt int userHandle) {
250 this(looper, context, netService, userHandle, new SystemServices(context));
251 }
252
253 @VisibleForTesting
254 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
255 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700256 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400257 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400258 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400259 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000260 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400261
262 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400263 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700264
265 try {
266 netService.registerObserver(mObserver);
267 } catch (RemoteException e) {
268 Log.wtf(TAG, "Problem registering observer", e);
269 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400270
Chalard Jeandd59ece2017-12-20 13:23:32 +0900271 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
272 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400273 mNetworkCapabilities = new NetworkCapabilities();
274 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
275 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600276 updateCapabilities();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000277
278 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700279 }
280
Jeff Sharkey57666932013-04-30 17:01:57 -0700281 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900282 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700283 * teardown. When {@code false}, teardown is handled externally by someone
284 * else.
285 */
286 public void setEnableTeardown(boolean enableTeardown) {
287 mEnableTeardown = enableTeardown;
288 }
289
Jeff Sharkey899223b2012-08-04 15:24:58 -0700290 /**
291 * Update current state, dispaching event to listeners.
292 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100293 @VisibleForTesting
294 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700295 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
296 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400297 if (mNetworkAgent != null) {
298 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
299 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100300 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700301 }
302
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600303 public void updateCapabilities() {
304 final Network[] underlyingNetworks = (mConfig != null) ? mConfig.underlyingNetworks : null;
305 updateCapabilities(mContext.getSystemService(ConnectivityManager.class), underlyingNetworks,
306 mNetworkCapabilities);
307
308 if (mNetworkAgent != null) {
309 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
310 }
311 }
312
313 @VisibleForTesting
314 public static void updateCapabilities(ConnectivityManager cm, Network[] underlyingNetworks,
315 NetworkCapabilities caps) {
316 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
317 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
318 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
319 boolean metered = false;
320 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900321 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600322
Chalard Jean3bd57052018-05-21 15:30:56 +0900323 boolean hadUnderlyingNetworks = false;
324 if (null != underlyingNetworks) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600325 for (Network underlying : underlyingNetworks) {
326 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700327 if (underlyingCaps == null) continue;
Chalard Jean3bd57052018-05-21 15:30:56 +0900328 hadUnderlyingNetworks = true;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600329 for (int underlyingType : underlyingCaps.getTransportTypes()) {
330 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
331 }
332
333 // When we have multiple networks, we have to assume the
334 // worst-case link speed and restrictions.
335 downKbps = NetworkCapabilities.minBandwidth(downKbps,
336 underlyingCaps.getLinkDownstreamBandwidthKbps());
337 upKbps = NetworkCapabilities.minBandwidth(upKbps,
338 underlyingCaps.getLinkUpstreamBandwidthKbps());
339 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
340 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900341 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600342 }
343 }
Chalard Jean3bd57052018-05-21 15:30:56 +0900344 if (!hadUnderlyingNetworks) {
345 // No idea what the underlying networks are; assume sane defaults
346 metered = true;
347 roaming = false;
348 congested = false;
349 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600350
351 caps.setTransportTypes(transportTypes);
352 caps.setLinkDownstreamBandwidthKbps(downKbps);
353 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900354 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
355 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
356 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600357 }
358
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700359 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000360 * Chooses whether to force all connections to go though VPN.
361 *
362 * Used to enable/disable legacy VPN lockdown.
363 *
364 * This uses the same ip rule mechanism as {@link #setAlwaysOnPackage(String, boolean)};
365 * previous settings from calling that function will be replaced and saved with the
366 * always-on state.
367 *
368 * @param lockdown whether to prevent all traffic outside of a VPN.
369 */
370 public synchronized void setLockdown(boolean lockdown) {
371 enforceControlPermissionOrInternalCaller();
372
373 setVpnForcedLocked(lockdown);
374 mLockdown = lockdown;
375
376 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
377 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
378 if (mAlwaysOn) {
379 saveAlwaysOnPackage();
380 }
381 }
382
383 /**
junyulai8ed89152018-10-25 10:56:17 +0800384 * Check whether to prevent all traffic outside of a VPN even when the VPN is not connected.
385 *
386 * @return {@code true} if VPN lockdown is enabled.
387 */
388 public boolean getLockdown() {
389 return mLockdown;
390 }
391
392 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100393 * Checks if a VPN app supports always-on mode.
394 *
395 * In order to support the always-on feature, an app has to
396 * <ul>
397 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100398 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
399 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100400 * </ul>
401 *
402 * @param packageName the canonical package name of the VPN app
403 * @return {@code true} if and only if the VPN app exists and supports always-on mode
404 */
405 public boolean isAlwaysOnPackageSupported(String packageName) {
406 enforceSettingsPermission();
407
408 if (packageName == null) {
409 return false;
410 }
411
412 PackageManager pm = mContext.getPackageManager();
413 ApplicationInfo appInfo = null;
414 try {
415 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
416 } catch (NameNotFoundException unused) {
417 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
418 }
419 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
420 return false;
421 }
422
423 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
424 intent.setPackage(packageName);
425 List<ResolveInfo> services =
426 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
427 if (services == null || services.size() == 0) {
428 return false;
429 }
430
431 for (ResolveInfo rInfo : services) {
432 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100433 if (metaData != null &&
434 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100435 return false;
436 }
437 }
438
439 return true;
440 }
441
442 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000443 * Configures an always-on VPN connection through a specific application.
444 * This connection is automatically granted and persisted after a reboot.
445 *
446 * <p>The designated package should exist and declare a {@link VpnService} in its
447 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
448 * otherwise the call will fail.
449 *
Charles Hea0a87e82017-05-15 17:07:18 +0100450 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
451 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
452 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
453 *
Robin Lee17e61832016-05-09 13:46:28 +0100454 * @param packageName the package to designate as always-on VPN supplier.
455 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100456 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000457 */
Robin Lee17e61832016-05-09 13:46:28 +0100458 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000459 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000460
461 if (setAlwaysOnPackageInternal(packageName, lockdown)) {
462 saveAlwaysOnPackage();
463 return true;
464 }
465 return false;
466 }
467
468 /**
469 * Configures an always-on VPN connection through a specific application, the same as
470 * {@link #setAlwaysOnPackage}.
471 *
472 * Does not perform permission checks. Does not persist any of the changes to storage.
473 *
474 * @param packageName the package to designate as always-on VPN supplier.
475 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
476 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
477 */
478 @GuardedBy("this")
479 private boolean setAlwaysOnPackageInternal(String packageName, boolean lockdown) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100480 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
481 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
482 return false;
483 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000484
Robin Lee244ce8e2016-01-05 18:03:46 +0000485 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100486 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000487 if (!setPackageAuthorization(packageName, true)) {
488 return false;
489 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100490 mAlwaysOn = true;
491 } else {
492 packageName = VpnConfig.LEGACY_VPN;
493 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000494 }
495
Robin Lee17e61832016-05-09 13:46:28 +0100496 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100497 if (isCurrentPreparedPackage(packageName)) {
498 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
499 } else {
500 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100501 prepareInternal(packageName);
502 }
Robin Lee812800c2016-05-13 15:38:08 +0100503 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100504 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000505 return true;
506 }
507
Robin Lee9ff1a582016-06-10 16:41:10 +0100508 private static boolean isNullOrLegacyVpn(String packageName) {
509 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
510 }
511
Robin Lee812800c2016-05-13 15:38:08 +0100512 private void unregisterPackageChangeReceiverLocked() {
Robin Lee812800c2016-05-13 15:38:08 +0100513 if (mIsPackageIntentReceiverRegistered) {
514 mContext.unregisterReceiver(mPackageIntentReceiver);
515 mIsPackageIntentReceiverRegistered = false;
516 }
517 }
518
519 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
520 // Unregister IntentFilter listening for previous always-on package change
521 unregisterPackageChangeReceiverLocked();
522
Robin Lee9ff1a582016-06-10 16:41:10 +0100523 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100524 mIsPackageIntentReceiverRegistered = true;
525
526 IntentFilter intentFilter = new IntentFilter();
527 // Protected intent can only be sent by system. No permission required in register.
528 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
529 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
530 intentFilter.addDataScheme("package");
531 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
532 mContext.registerReceiverAsUser(
533 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
534 }
535 }
536
Robin Lee244ce8e2016-01-05 18:03:46 +0000537 /**
538 * @return the package name of the VPN controller responsible for always-on VPN,
539 * or {@code null} if none is set or always-on VPN is controlled through
540 * lockdown instead.
541 * @hide
542 */
543 public synchronized String getAlwaysOnPackage() {
544 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100545 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000546 }
547
548 /**
Robin Lee812800c2016-05-13 15:38:08 +0100549 * Save the always-on package and lockdown config into Settings.Secure
550 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000551 @GuardedBy("this")
552 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100553 final long token = Binder.clearCallingIdentity();
554 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000555 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100556 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000557 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000558 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100559 } finally {
560 Binder.restoreCallingIdentity(token);
561 }
562 }
563
564 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000565 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100566 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000567 @GuardedBy("this")
568 private void loadAlwaysOnPackage() {
569 final long token = Binder.clearCallingIdentity();
570 try {
571 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
572 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
573 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
574 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
575 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown);
576 } finally {
577 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100578 }
579 }
580
581 /**
582 * @return {@code true} if the service was started, the service was already connected, or there
583 * was no always-on VPN to start. {@code false} otherwise.
584 */
585 public boolean startAlwaysOnVpn() {
586 final String alwaysOnPackage;
587 synchronized (this) {
588 alwaysOnPackage = getAlwaysOnPackage();
589 // Skip if there is no service to start.
590 if (alwaysOnPackage == null) {
591 return true;
592 }
Charles Hea0a87e82017-05-15 17:07:18 +0100593 // Remove always-on VPN if it's not supported.
594 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
595 setAlwaysOnPackage(null, false);
596 return false;
597 }
Robin Lee812800c2016-05-13 15:38:08 +0100598 // Skip if the service is already established. This isn't bulletproof: it's not bound
599 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
600 // which may restart the connection.
601 if (getNetworkInfo().isConnected()) {
602 return true;
603 }
604 }
605
Christopher Tatee0be7e82017-02-08 17:38:20 -0800606 // Tell the OS that background services in this app need to be allowed for
607 // a short time, so we can bootstrap the VPN service.
608 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100609 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800610 DeviceIdleController.LocalService idleController =
611 LocalServices.getService(DeviceIdleController.LocalService.class);
612 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900613 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800614
615 // Start the VPN service declared in the app's manifest.
616 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
617 serviceIntent.setPackage(alwaysOnPackage);
618 try {
619 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
620 } catch (RuntimeException e) {
621 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
622 return false;
623 }
624 } finally {
625 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100626 }
627 }
628
629 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700630 * Prepare for a VPN application. This method is designed to solve
631 * race conditions. It first compares the current prepared package
632 * with {@code oldPackage}. If they are the same, the prepared
633 * package is revoked and replaced with {@code newPackage}. If
634 * {@code oldPackage} is {@code null}, the comparison is omitted.
635 * If {@code newPackage} is the same package or {@code null}, the
636 * revocation is omitted. This method returns {@code true} if the
637 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700638 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700639 * Legacy VPN is handled specially since it is not a real package.
640 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
641 * it can be revoked by itself.
642 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900643 * Note: when we added VPN pre-consent in
644 * https://android.googlesource.com/platform/frameworks/base/+/0554260
645 * the names oldPackage and newPackage became misleading, because when
646 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100647 *
648 * Their meanings actually are:
649 *
650 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
651 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100652 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100653 * and revoke any current app VPN and re-prepare legacy vpn.
654 *
Robin Lee812800c2016-05-13 15:38:08 +0100655 * TODO: Rename the variables - or split this method into two - and end this confusion.
656 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
657 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100658 *
659 * @param oldPackage The package name of the old VPN application
660 * @param newPackage The package name of the new VPN application
661 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900662 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700663 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700664 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700665 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100666 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100667 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100668 return false;
669 }
670
Chalard Jeandd59ece2017-12-20 13:23:32 +0900671 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100672 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700673 // The package doesn't match. We return false (to obtain user consent) unless the
674 // user has already consented to that VPN package.
675 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
676 prepareInternal(oldPackage);
677 return true;
678 }
679 return false;
680 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
681 && !isVpnUserPreConsented(oldPackage)) {
682 // Currently prepared VPN is revoked, so unprepare it and return false.
683 prepareInternal(VpnConfig.LEGACY_VPN);
684 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700685 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700686 }
687
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700688 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700689 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100690 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700691 return true;
692 }
693
Robin Lee1b1bcd72016-02-12 18:11:30 +0000694 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700695 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700696
Victor Chang98a633a2016-05-27 17:30:49 +0100697 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100698 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100699 return false;
700 }
701
Jeff Davidson11008a72014-11-20 13:12:46 -0800702 prepareInternal(newPackage);
703 return true;
704 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700705
Victor Chang98a633a2016-05-27 17:30:49 +0100706 private boolean isCurrentPreparedPackage(String packageName) {
707 // We can't just check that packageName matches mPackage, because if the app was uninstalled
708 // and reinstalled it will no longer be prepared. Instead check the UID.
709 return getAppUid(packageName, mUserHandle) == mOwnerUID;
710 }
711
Jeff Davidson11008a72014-11-20 13:12:46 -0800712 /** Prepare the VPN for the given package. Does not perform permission checks. */
713 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400714 long token = Binder.clearCallingIdentity();
715 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800716 // Reset the interface.
717 if (mInterface != null) {
718 mStatusIntent = null;
719 agentDisconnect();
720 jniReset(mInterface);
721 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900722 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800723 }
724
725 // Revoke the connection or stop LegacyVpnRunner.
726 if (mConnection != null) {
727 try {
728 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
729 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
730 } catch (Exception e) {
731 // ignore
732 }
733 mContext.unbindService(mConnection);
734 mConnection = null;
735 } else if (mLegacyVpnRunner != null) {
736 mLegacyVpnRunner.exit();
737 mLegacyVpnRunner = null;
738 }
739
740 try {
741 mNetd.denyProtect(mOwnerUID);
742 } catch (Exception e) {
743 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
744 }
745
746 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
747 mPackage = newPackage;
748 mOwnerUID = getAppUid(newPackage, mUserHandle);
749 try {
750 mNetd.allowProtect(mOwnerUID);
751 } catch (Exception e) {
752 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
753 }
754 mConfig = null;
755
756 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000757 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400758 } finally {
759 Binder.restoreCallingIdentity(token);
760 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700761 }
762
Jeff Davidson05542602014-08-11 14:07:27 -0700763 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100764 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700765 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000766 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700767 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000768 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700769
Robin Lee3b3dd942015-05-12 18:14:58 +0100770 int uid = getAppUid(packageName, mUserHandle);
771 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
772 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000773 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700774 }
775
776 long token = Binder.clearCallingIdentity();
777 try {
778 AppOpsManager appOps =
779 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100780 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700781 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000782 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700783 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100784 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700785 } finally {
786 Binder.restoreCallingIdentity(token);
787 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000788 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700789 }
790
791 private boolean isVpnUserPreConsented(String packageName) {
792 AppOpsManager appOps =
793 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
794
795 // Verify that the caller matches the given package and has permission to activate VPNs.
796 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
797 packageName) == AppOpsManager.MODE_ALLOWED;
798 }
799
Paul Jensen0784eea2014-08-19 16:00:24 -0400800 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700801 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400802 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700803 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400804 PackageManager pm = mContext.getPackageManager();
805 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700806 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700807 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400808 } catch (NameNotFoundException e) {
809 result = -1;
810 }
811 return result;
812 }
813
814 public NetworkInfo getNetworkInfo() {
815 return mNetworkInfo;
816 }
817
Paul Jensen31a94f42015-02-13 14:18:39 -0500818 public int getNetId() {
819 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
820 }
821
Lorenzo Colitti60446162014-09-20 00:14:31 +0900822 private LinkProperties makeLinkProperties() {
823 boolean allowIPv4 = mConfig.allowIPv4;
824 boolean allowIPv6 = mConfig.allowIPv6;
825
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400826 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900827
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400828 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700829
Lorenzo Colitti60446162014-09-20 00:14:31 +0900830 if (mConfig.addresses != null) {
831 for (LinkAddress address : mConfig.addresses) {
832 lp.addLinkAddress(address);
833 allowIPv4 |= address.getAddress() instanceof Inet4Address;
834 allowIPv6 |= address.getAddress() instanceof Inet6Address;
835 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400836 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900837
838 if (mConfig.routes != null) {
839 for (RouteInfo route : mConfig.routes) {
840 lp.addRoute(route);
841 InetAddress address = route.getDestination().getAddress();
842 allowIPv4 |= address instanceof Inet4Address;
843 allowIPv6 |= address instanceof Inet6Address;
844 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400845 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700846
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400847 if (mConfig.dnsServers != null) {
848 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700849 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
850 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900851 allowIPv4 |= address instanceof Inet4Address;
852 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400853 }
854 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700855
Lorenzo Colitti60446162014-09-20 00:14:31 +0900856 if (!allowIPv4) {
857 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
858 }
859 if (!allowIPv6) {
860 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
861 }
862
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400863 // Concatenate search domains into a string.
864 StringBuilder buffer = new StringBuilder();
865 if (mConfig.searchDomains != null) {
866 for (String domain : mConfig.searchDomains) {
867 buffer.append(domain).append(' ');
868 }
869 }
870 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700871
Lorenzo Colitti60446162014-09-20 00:14:31 +0900872 // TODO: Stop setting the MTU in jniCreate and set it here.
873
874 return lp;
875 }
876
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900877 /**
878 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
879 *
880 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
881 * space or to most of the IPv6 address space, where "most" is defined by the value of the
882 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
883 * by any of the routes, then it's decided that most of the space is routed.
884 * @hide
885 */
886 @VisibleForTesting
887 static boolean providesRoutesToMostDestinations(LinkProperties lp) {
Chalard Jeane0d26f62018-03-29 14:10:44 +0900888 final List<RouteInfo> routes = lp.getAllRoutes();
889 if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900890 final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
891 TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
892 TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
Chalard Jeane0d26f62018-03-29 14:10:44 +0900893 for (final RouteInfo route : routes) {
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900894 IpPrefix destination = route.getDestination();
895 if (destination.isIPv4()) {
896 ipv4Prefixes.add(destination);
897 } else {
898 ipv6Prefixes.add(destination);
899 }
900 }
901 if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
902 return true;
903 }
904 return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
905 .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
906 }
907
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900908 /**
909 * Attempt to perform a seamless handover of VPNs by only updating LinkProperties without
910 * registering a new NetworkAgent. This is not always possible if the new VPN configuration
911 * has certain changes, in which case this method would just return {@code false}.
912 */
913 private boolean updateLinkPropertiesInPlaceIfPossible(NetworkAgent agent, VpnConfig oldConfig) {
914 // NetworkMisc cannot be updated without registering a new NetworkAgent.
915 if (oldConfig.allowBypass != mConfig.allowBypass) {
916 Log.i(TAG, "Handover not possible due to changes to allowBypass");
917 return false;
918 }
919
920 // TODO: we currently do not support seamless handover if the allowed or disallowed
921 // applications have changed. Consider diffing UID ranges and only applying the delta.
922 if (!Objects.equals(oldConfig.allowedApplications, mConfig.allowedApplications) ||
923 !Objects.equals(oldConfig.disallowedApplications, mConfig.disallowedApplications)) {
924 Log.i(TAG, "Handover not possible due to changes to whitelisted/blacklisted apps");
925 return false;
926 }
927
928 LinkProperties lp = makeLinkProperties();
929 final boolean hadInternetCapability = mNetworkCapabilities.hasCapability(
930 NetworkCapabilities.NET_CAPABILITY_INTERNET);
931 final boolean willHaveInternetCapability = providesRoutesToMostDestinations(lp);
932 if (hadInternetCapability != willHaveInternetCapability) {
933 // A seamless handover would have led to a change to INTERNET capability, which
934 // is supposed to be immutable for a given network. In this case bail out and do not
935 // perform handover.
936 Log.i(TAG, "Handover not possible due to changes to INTERNET capability");
937 return false;
938 }
939
940 agent.sendLinkProperties(lp);
941 return true;
942 }
943
Lorenzo Colitti60446162014-09-20 00:14:31 +0900944 private void agentConnect() {
945 LinkProperties lp = makeLinkProperties();
946
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900947 if (providesRoutesToMostDestinations(lp)) {
Lorenzo Colitti60446162014-09-20 00:14:31 +0900948 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
949 } else {
950 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
951 }
952
Robin Lee323f29d2016-05-04 16:38:06 +0100953 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700954
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700955 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100956 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700957
Chalard Jeanf474fc32018-01-17 15:10:05 +0900958 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900959 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
960 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400961 long token = Binder.clearCallingIdentity();
962 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900963 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900964 mNetworkInfo, mNetworkCapabilities, lp,
965 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700966 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400967 public void unwanted() {
968 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700969 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400970 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700971 } finally {
972 Binder.restoreCallingIdentity(token);
973 }
Robin Lee323f29d2016-05-04 16:38:06 +0100974 mNetworkInfo.setIsAvailable(true);
975 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400976 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700977
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700978 private boolean canHaveRestrictedProfile(int userId) {
979 long token = Binder.clearCallingIdentity();
980 try {
981 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
982 } finally {
983 Binder.restoreCallingIdentity(token);
984 }
985 }
986
Tony Mak1a405fe2016-06-30 11:19:20 +0100987 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400988 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100989 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
990 networkInfo.setIsAvailable(false);
991 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400992 networkAgent.sendNetworkInfo(networkInfo);
993 }
994 }
995
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400996 private void agentDisconnect() {
997 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100998 mNetworkInfo.setIsAvailable(false);
999 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001000 mNetworkAgent = null;
1001 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001002 }
1003
1004 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -07001005 * Establish a VPN network and return the file descriptor of the VPN
1006 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001007 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -07001008 *
1009 * @param config The parameters to configure the network.
1010 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001011 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07001012 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001013 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -07001014 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001015 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -07001016 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001017 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -07001018 // Check to ensure consent hasn't been revoked since we were prepared.
1019 if (!isVpnUserPreConsented(mPackage)) {
1020 return null;
1021 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001022 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001023 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
1024 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001025 long token = Binder.clearCallingIdentity();
1026 try {
Chad Brubakerc2865192013-07-10 14:46:23 -07001027 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -04001028 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +01001029 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001030 throw new SecurityException("Restricted users cannot establish VPNs");
1031 }
1032
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001033 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +09001034 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001035 if (info == null) {
1036 throw new SecurityException("Cannot find " + config.user);
1037 }
1038 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
1039 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
1040 }
1041 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001042 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001043 } finally {
1044 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001045 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -07001046
Chad Brubaker850eb672014-03-21 21:02:47 +00001047 // Save the old config in case we need to go back.
1048 VpnConfig oldConfig = mConfig;
1049 String oldInterface = mInterface;
1050 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001051 NetworkAgent oldNetworkAgent = mNetworkAgent;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001052 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +00001053
Chia-chi Yehe9107902011-07-02 01:48:50 -07001054 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001055 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001056 try {
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001057 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001058
Chad Brubakerc2865192013-07-10 14:46:23 -07001059 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001060 StringBuilder builder = new StringBuilder();
1061 for (LinkAddress address : config.addresses) {
1062 builder.append(" " + address);
1063 }
1064 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001065 throw new IllegalArgumentException("At least one address must be specified");
1066 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001067 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001068 if (!mContext.bindServiceAsUser(intent, connection,
1069 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1070 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001071 throw new IllegalStateException("Cannot bind " + config.user);
1072 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001073
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001074 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001075 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001076
1077 // Fill more values.
1078 config.user = mPackage;
1079 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001080 config.startTime = SystemClock.elapsedRealtime();
1081 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001082
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001083 // Set up forwarding and DNS rules.
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001084 // First attempt to do a seamless handover that only changes the interface name and
1085 // parameters. If that fails, disconnect.
1086 if (oldConfig != null
1087 && updateLinkPropertiesInPlaceIfPossible(mNetworkAgent, oldConfig)) {
1088 // Keep mNetworkAgent unchanged
1089 } else {
1090 mNetworkAgent = null;
1091 updateState(DetailedState.CONNECTING, "establish");
1092 // Set up forwarding and DNS rules.
1093 agentConnect();
1094 // Remove the old tun's user forwarding rules
1095 // The new tun's user rules have already been added above so they will take over
1096 // as rules are deleted. This prevents data leakage as the rules are moved over.
1097 agentDisconnect(oldNetworkAgent);
1098 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001099
1100 if (oldConnection != null) {
1101 mContext.unbindService(oldConnection);
1102 }
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001103
Chad Brubaker850eb672014-03-21 21:02:47 +00001104 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001105 jniReset(oldInterface);
1106 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001107
1108 try {
1109 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1110 } catch (IOException e) {
1111 throw new IllegalStateException(
1112 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1113 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001114 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001115 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001116 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001117 // restore old state
1118 mConfig = oldConfig;
1119 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001120 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001121 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001122 mInterface = oldInterface;
1123 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001124 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001125 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001126 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001127 }
1128
Chad Brubakerc2865192013-07-10 14:46:23 -07001129 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001130 return mNetworkAgent != null && mInterface != null;
1131 }
1132
1133 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1134 // that a call to mutate VPN state is admissible.
Chalard Jeanf666d0a2018-05-18 21:47:45 +09001135 @VisibleForTesting
1136 protected boolean isCallerEstablishedOwnerLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001137 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001138 }
1139
Paul Jensen0784eea2014-08-19 16:00:24 -04001140 // Note: Return type guarantees results are deduped and sorted, which callers require.
1141 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
1142 SortedSet<Integer> uids = new TreeSet<Integer>();
1143 for (String app : packageNames) {
1144 int uid = getAppUid(app, userHandle);
1145 if (uid != -1) uids.add(uid);
1146 }
1147 return uids;
1148 }
1149
Robin Lee4d03abc2016-05-09 12:32:27 +01001150 /**
1151 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1152 * associated with one user, and any restricted profiles attached to that user.
1153 *
1154 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1155 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1156 * in each user and profile will be included.
1157 *
1158 * @param userHandle The userId to create UID ranges for along with any of its restricted
1159 * profiles.
1160 * @param allowedApplications (optional) whitelist of applications to include.
1161 * @param disallowedApplications (optional) blacklist of applications to exclude.
1162 */
1163 @VisibleForTesting
1164 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1165 @Nullable List<String> allowedApplications,
1166 @Nullable List<String> disallowedApplications) {
1167 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001168
Robin Lee4d03abc2016-05-09 12:32:27 +01001169 // Assign the top-level user to the set of ranges
1170 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1171
1172 // If the user can have restricted profiles, assign all its restricted profiles too
1173 if (canHaveRestrictedProfile(userHandle)) {
1174 final long token = Binder.clearCallingIdentity();
1175 List<UserInfo> users;
1176 try {
Robin Lee17e61832016-05-09 13:46:28 +01001177 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001178 } finally {
1179 Binder.restoreCallingIdentity(token);
1180 }
1181 for (UserInfo user : users) {
1182 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1183 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1184 }
1185 }
1186 }
1187 return ranges;
1188 }
1189
1190 /**
1191 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1192 * associated with one user.
1193 *
1194 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1195 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1196 * in the user will be included.
1197 *
1198 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1199 * @param userHandle The userId to add to {@param ranges}.
1200 * @param allowedApplications (optional) whitelist of applications to include.
1201 * @param disallowedApplications (optional) blacklist of applications to exclude.
1202 */
1203 @VisibleForTesting
1204 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1205 @Nullable List<String> allowedApplications,
1206 @Nullable List<String> disallowedApplications) {
1207 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001208 // Add ranges covering all UIDs for allowedApplications.
1209 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001210 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001211 if (start == -1) {
1212 start = uid;
1213 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001214 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001215 start = uid;
1216 }
1217 stop = uid;
1218 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001219 if (start != -1) ranges.add(new UidRange(start, stop));
1220 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001221 // Add all ranges for user skipping UIDs for disallowedApplications.
1222 final UidRange userRange = UidRange.createForUser(userHandle);
1223 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001224 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001225 if (uid == start) {
1226 start++;
1227 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001228 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001229 start = uid + 1;
1230 }
1231 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001232 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001233 } else {
1234 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001235 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001236 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001237 }
1238
Paul Jensen0784eea2014-08-19 16:00:24 -04001239 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1240 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001241 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1242 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1243 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001244 final UidRange userRange = UidRange.createForUser(userHandle);
1245 final List<UidRange> ranges = new ArrayList<UidRange>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001246 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001247 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001248 ranges.add(range);
1249 }
1250 }
1251 return ranges;
1252 }
1253
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001254 public void onUserAdded(int userHandle) {
1255 // If the user is restricted tie them to the parent user's VPN
1256 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001257 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001258 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001259 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1260 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001261 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001262 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001263 mConfig.disallowedApplications);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001264 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001265 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001266 } catch (Exception e) {
1267 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001268 }
Robin Lee17e61832016-05-09 13:46:28 +01001269 }
Robin Leec3736bc2017-03-10 16:19:54 +00001270 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001271 }
1272 }
1273 }
1274
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001275 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001276 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001277 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001278 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001279 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001280 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1281 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001282 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001283 final List<UidRange> removedRanges =
1284 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001285 existingRanges.removeAll(removedRanges);
1286 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001287 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001288 } catch (Exception e) {
1289 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1290 }
1291 }
Robin Leec3736bc2017-03-10 16:19:54 +00001292 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001293 }
1294 }
1295 }
1296
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001297 /**
Robin Lee17e61832016-05-09 13:46:28 +01001298 * Called when the user associated with this VPN has just been stopped.
1299 */
1300 public synchronized void onUserStopped() {
1301 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001302 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001303 mAlwaysOn = false;
1304
Robin Lee812800c2016-05-13 15:38:08 +01001305 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001306 // Quit any active connections
1307 agentDisconnect();
1308 }
1309
1310 /**
1311 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1312 * service app itself, to only sockets that have had {@code protect()} called on them. All
1313 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1314 *
1315 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1316 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1317 *
1318 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1319 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1320 *
1321 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1322 * {@link Vpn} goes through a VPN connection or is blocked until one is
1323 * available, {@code false} to lift the requirement.
1324 *
1325 * @see #mBlockedUsers
1326 */
1327 @GuardedBy("this")
1328 private void setVpnForcedLocked(boolean enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001329 final List<String> exemptedPackages =
1330 isNullOrLegacyVpn(mPackage) ? null : Collections.singletonList(mPackage);
Robin Lee17e61832016-05-09 13:46:28 +01001331 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
Robin Leec3736bc2017-03-10 16:19:54 +00001332
1333 Set<UidRange> addedRanges = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001334 if (enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001335 addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
Robin Lee17e61832016-05-09 13:46:28 +01001336 /* allowedApplications */ null,
Robin Leec3736bc2017-03-10 16:19:54 +00001337 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001338
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001339 // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
1340 // directly from the kernel and is marked as uid=0. So we adjust the range to allow
1341 // it through (b/69873852).
1342 for (UidRange range : addedRanges) {
1343 if (range.start == 0) {
1344 addedRanges.remove(range);
1345 if (range.stop != 0) {
1346 addedRanges.add(new UidRange(1, range.stop));
1347 }
1348 }
1349 }
1350
Robin Lee17e61832016-05-09 13:46:28 +01001351 removedRanges.removeAll(addedRanges);
1352 addedRanges.removeAll(mBlockedUsers);
Robin Lee17e61832016-05-09 13:46:28 +01001353 }
Robin Leec3736bc2017-03-10 16:19:54 +00001354
1355 setAllowOnlyVpnForUids(false, removedRanges);
1356 setAllowOnlyVpnForUids(true, addedRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001357 }
1358
1359 /**
1360 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1361 * to make connections through sockets that have had {@code protect()} called on them.
1362 *
1363 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1364 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1365 * {@code true}) or to remove.
1366 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1367 * including added ranges that already existed or removed ones that didn't.
1368 */
1369 @GuardedBy("this")
1370 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1371 if (ranges.size() == 0) {
1372 return true;
1373 }
1374 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1375 try {
1376 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1377 } catch (RemoteException | RuntimeException e) {
1378 Log.e(TAG, "Updating blocked=" + enforce
1379 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1380 return false;
1381 }
1382 if (enforce) {
1383 mBlockedUsers.addAll(ranges);
1384 } else {
1385 mBlockedUsers.removeAll(ranges);
1386 }
1387 return true;
1388 }
1389
1390 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001391 * Return the configuration of the currently running VPN.
1392 */
1393 public VpnConfig getVpnConfig() {
1394 enforceControlPermission();
1395 return mConfig;
1396 }
1397
Jeff Sharkey899223b2012-08-04 15:24:58 -07001398 @Deprecated
1399 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1400 try {
1401 mObserver.interfaceStatusChanged(iface, up);
1402 } catch (RemoteException e) {
1403 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001404 }
1405 }
1406
Jeff Sharkey899223b2012-08-04 15:24:58 -07001407 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1408 @Override
1409 public void interfaceStatusChanged(String interfaze, boolean up) {
1410 synchronized (Vpn.this) {
1411 if (!up && mLegacyVpnRunner != null) {
1412 mLegacyVpnRunner.check(interfaze);
1413 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001414 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001415 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001416
Jeff Sharkey899223b2012-08-04 15:24:58 -07001417 @Override
1418 public void interfaceRemoved(String interfaze) {
1419 synchronized (Vpn.this) {
1420 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001421 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001422 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001423 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001424 mInterface = null;
1425 if (mConnection != null) {
1426 mContext.unbindService(mConnection);
1427 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001428 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001429 } else if (mLegacyVpnRunner != null) {
1430 mLegacyVpnRunner.exit();
1431 mLegacyVpnRunner = null;
1432 }
1433 }
1434 }
1435 }
1436 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001437
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001438 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001439 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001440 }
1441
Robin Lee244ce8e2016-01-05 18:03:46 +00001442 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001443 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001444 // in the system server.
1445 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1446 "Unauthorized Caller");
1447 }
1448
Charles Hea0a87e82017-05-15 17:07:18 +01001449 private void enforceSettingsPermission() {
1450 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1451 "Unauthorized Caller");
1452 }
1453
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001454 private class Connection implements ServiceConnection {
1455 private IBinder mService;
1456
1457 @Override
1458 public void onServiceConnected(ComponentName name, IBinder service) {
1459 mService = service;
1460 }
1461
1462 @Override
1463 public void onServiceDisconnected(ComponentName name) {
1464 mService = null;
1465 }
1466 }
1467
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001468 private void prepareStatusIntent() {
1469 final long token = Binder.clearCallingIdentity();
1470 try {
1471 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1472 } finally {
1473 Binder.restoreCallingIdentity(token);
1474 }
1475 }
1476
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001477 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001478 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001479 return false;
1480 }
1481 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001482 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001483 return success;
1484 }
1485
1486 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001487 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001488 return false;
1489 }
1490 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001491 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001492 return success;
1493 }
1494
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001495 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1496 if (!isCallerEstablishedOwnerLocked()) {
1497 return false;
1498 }
1499 if (networks == null) {
1500 mConfig.underlyingNetworks = null;
1501 } else {
1502 mConfig.underlyingNetworks = new Network[networks.length];
1503 for (int i = 0; i < networks.length; ++i) {
1504 if (networks[i] == null) {
1505 mConfig.underlyingNetworks[i] = null;
1506 } else {
1507 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1508 }
1509 }
1510 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001511 updateCapabilities();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001512 return true;
1513 }
1514
1515 public synchronized Network[] getUnderlyingNetworks() {
1516 if (!isRunningLocked()) {
1517 return null;
1518 }
1519 return mConfig.underlyingNetworks;
1520 }
1521
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001522 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001523 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001524 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1525 */
1526 public synchronized VpnInfo getVpnInfo() {
1527 if (!isRunningLocked()) {
1528 return null;
1529 }
1530
1531 VpnInfo info = new VpnInfo();
1532 info.ownerUid = mOwnerUID;
1533 info.vpnIface = mInterface;
1534 return info;
1535 }
1536
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001537 public synchronized boolean appliesToUid(int uid) {
1538 if (!isRunningLocked()) {
1539 return false;
1540 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001541 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001542 }
1543
Robin Lee17e61832016-05-09 13:46:28 +01001544 /**
junyulai8ed89152018-10-25 10:56:17 +08001545 * @param uid The target uid.
Robin Lee17e61832016-05-09 13:46:28 +01001546 *
junyulai8ed89152018-10-25 10:56:17 +08001547 * @return {@code true} if {@code uid} is included in one of the mBlockedUsers ranges and the
1548 * VPN is not connected, or if the VPN is connected but does not apply to the {@code uid}.
1549 *
1550 * @apiNote This method don't check VPN lockdown status.
Robin Lee17e61832016-05-09 13:46:28 +01001551 * @see #mBlockedUsers
1552 */
1553 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001554 if (mNetworkInfo.isConnected()) {
1555 return !appliesToUid(uid);
1556 } else {
1557 for (UidRange uidRange : mBlockedUsers) {
1558 if (uidRange.contains(uid)) {
1559 return true;
1560 }
1561 }
1562 return false;
1563 }
Robin Lee17e61832016-05-09 13:46:28 +01001564 }
1565
Tony Mak1a405fe2016-06-30 11:19:20 +01001566 private void updateAlwaysOnNotification(DetailedState networkState) {
1567 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001568
Tony Mak1a405fe2016-06-30 11:19:20 +01001569 final UserHandle user = UserHandle.of(mUserHandle);
1570 final long token = Binder.clearCallingIdentity();
1571 try {
1572 final NotificationManager notificationManager = NotificationManager.from(mContext);
1573 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001574 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001575 return;
1576 }
Charles Heab6f2f62017-07-12 15:30:00 +01001577 final Intent intent = new Intent();
1578 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1579 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1580 intent.putExtra("lockdown", mLockdown);
1581 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001582 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1583 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001584 final Notification.Builder builder =
1585 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1586 .setSmallIcon(R.drawable.vpn_connected)
1587 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1588 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1589 .setContentIntent(configIntent)
1590 .setCategory(Notification.CATEGORY_SYSTEM)
1591 .setVisibility(Notification.VISIBILITY_PUBLIC)
1592 .setOngoing(true)
1593 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001594 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1595 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001596 } finally {
1597 Binder.restoreCallingIdentity(token);
1598 }
1599 }
1600
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001601 /**
1602 * Facade for system service calls that change, or depend on, state outside of
1603 * {@link ConnectivityService} and have hard-to-mock interfaces.
1604 *
1605 * @see com.android.server.connectivity.VpnTest
1606 */
1607 @VisibleForTesting
1608 public static class SystemServices {
1609 private final Context mContext;
1610
1611 public SystemServices(@NonNull Context context) {
1612 mContext = context;
1613 }
1614
1615 /**
1616 * @see PendingIntent#getActivityAsUser()
1617 */
1618 public PendingIntent pendingIntentGetActivityAsUser(
1619 Intent intent, int flags, UserHandle user) {
1620 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1621 null /*options*/, user);
1622 }
1623
1624 /**
1625 * @see Settings.Secure#putStringForUser
1626 */
1627 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1628 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1629 }
1630
1631 /**
1632 * @see Settings.Secure#putIntForUser
1633 */
1634 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1635 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1636 }
1637
1638 /**
1639 * @see Settings.Secure#getStringForUser
1640 */
1641 public String settingsSecureGetStringForUser(String key, int userId) {
1642 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1643 }
1644
1645 /**
1646 * @see Settings.Secure#getIntForUser
1647 */
1648 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1649 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1650 }
1651 }
1652
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001653 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001654 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001655 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001656 private native void jniReset(String interfaze);
1657 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001658 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1659 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001660
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001661 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1662 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001663 // Currently legacy VPN only works on IPv4.
1664 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001665 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001666 }
1667 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001668
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001669 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001670 }
1671
1672 /**
1673 * Start legacy VPN, controlling native daemons as needed. Creates a
1674 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001675 *
1676 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1677 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1678 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001679 */
1680 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001681 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001682 long token = Binder.clearCallingIdentity();
1683 try {
1684 startLegacyVpnPrivileged(profile, keyStore, egress);
1685 } finally {
1686 Binder.restoreCallingIdentity(token);
1687 }
1688 }
1689
1690 /**
1691 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1692 * permissions under the assumption that the caller is the system.
1693 *
1694 * Callers are responsible for checking permissions if needed.
1695 */
1696 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1697 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001698 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001699 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001700 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1701 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001702 throw new SecurityException("Restricted users cannot establish VPNs");
1703 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001704
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001705 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1706 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1707 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001708
1709 // Load certificates.
1710 String privateKey = "";
1711 String userCert = "";
1712 String caCert = "";
1713 String serverCert = "";
1714 if (!profile.ipsecUserCert.isEmpty()) {
1715 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1716 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001717 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001718 }
1719 if (!profile.ipsecCaCert.isEmpty()) {
1720 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001721 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001722 }
1723 if (!profile.ipsecServerCert.isEmpty()) {
1724 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001725 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001726 }
1727 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1728 throw new IllegalStateException("Cannot load credentials");
1729 }
1730
1731 // Prepare arguments for racoon.
1732 String[] racoon = null;
1733 switch (profile.type) {
1734 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1735 racoon = new String[] {
1736 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1737 profile.ipsecSecret, "1701",
1738 };
1739 break;
1740 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1741 racoon = new String[] {
1742 iface, profile.server, "udprsa", privateKey, userCert,
1743 caCert, serverCert, "1701",
1744 };
1745 break;
1746 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1747 racoon = new String[] {
1748 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1749 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1750 };
1751 break;
1752 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1753 racoon = new String[] {
1754 iface, profile.server, "xauthrsa", privateKey, userCert,
1755 caCert, serverCert, profile.username, profile.password, "", gateway,
1756 };
1757 break;
1758 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1759 racoon = new String[] {
1760 iface, profile.server, "hybridrsa",
1761 caCert, serverCert, profile.username, profile.password, "", gateway,
1762 };
1763 break;
1764 }
1765
1766 // Prepare arguments for mtpd.
1767 String[] mtpd = null;
1768 switch (profile.type) {
1769 case VpnProfile.TYPE_PPTP:
1770 mtpd = new String[] {
1771 iface, "pptp", profile.server, "1723",
1772 "name", profile.username, "password", profile.password,
1773 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1774 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1775 (profile.mppe ? "+mppe" : "nomppe"),
1776 };
1777 break;
1778 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1779 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1780 mtpd = new String[] {
1781 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1782 "name", profile.username, "password", profile.password,
1783 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1784 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1785 };
1786 break;
1787 }
1788
1789 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001790 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001791 config.user = profile.key;
1792 config.interfaze = iface;
1793 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001794
1795 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001796 if (!profile.dnsServers.isEmpty()) {
1797 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1798 }
1799 if (!profile.searchDomains.isEmpty()) {
1800 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1801 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001802 startLegacyVpn(config, racoon, mtpd);
1803 }
1804
1805 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001806 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001807
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001808 // Prepare for the new request.
1809 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001810 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001811
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001812 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001813 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1814 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001815 }
1816
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001817 /** Stop legacy VPN. Permissions must be checked by callers. */
1818 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001819 if (mLegacyVpnRunner != null) {
1820 mLegacyVpnRunner.exit();
1821 mLegacyVpnRunner = null;
1822
1823 synchronized (LegacyVpnRunner.TAG) {
1824 // wait for old thread to completely finish before spinning up
1825 // new instance, otherwise state updates can be out of order.
1826 }
1827 }
1828 }
1829
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001830 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001831 * Return the information of the current ongoing legacy VPN.
1832 */
1833 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001834 // Check if the caller is authorized.
1835 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001836 return getLegacyVpnInfoPrivileged();
1837 }
1838
1839 /**
1840 * Return the information of the current ongoing legacy VPN.
1841 * Callers are responsible for checking permissions if needed.
1842 */
1843 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001844 if (mLegacyVpnRunner == null) return null;
1845
1846 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001847 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001848 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001849 if (mNetworkInfo.isConnected()) {
1850 info.intent = mStatusIntent;
1851 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001852 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001853 }
1854
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001855 public VpnConfig getLegacyVpnConfig() {
1856 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001857 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001858 } else {
1859 return null;
1860 }
1861 }
1862
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001863 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001864 * Bringing up a VPN connection takes time, and that is all this thread
1865 * does. Here we have plenty of time. The only thing we need to take
1866 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001867 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001868 * machine, but it is much easier to read in the current form.
1869 */
1870 private class LegacyVpnRunner extends Thread {
1871 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001872
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001873 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001874 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001875 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001876 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001877 private final AtomicInteger mOuterConnection =
1878 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001879
Chalard Jeandd59ece2017-12-20 13:23:32 +09001880 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001881
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001882 /**
1883 * Watch for the outer connection (passing in the constructor) going away.
1884 */
1885 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1886 @Override
1887 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001888 if (!mEnableTeardown) return;
1889
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001890 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1891 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1892 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1893 NetworkInfo info = (NetworkInfo)intent.getExtra(
1894 ConnectivityManager.EXTRA_NETWORK_INFO);
1895 if (info != null && !info.isConnectedOrConnecting()) {
1896 try {
1897 mObserver.interfaceStatusChanged(mOuterInterface, false);
1898 } catch (RemoteException e) {}
1899 }
1900 }
1901 }
1902 }
1903 };
1904
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001905 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001906 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001907 mConfig = config;
1908 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001909 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001910 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001911 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001912
1913 // This is the interface which VPN is running on,
1914 // mConfig.interfaze will change to point to OUR
1915 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001916 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001917 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001918 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001919 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001920
Paul Jensene75b9e32015-04-06 11:54:53 -04001921 if (!TextUtils.isEmpty(mOuterInterface)) {
1922 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1923 for (Network network : cm.getAllNetworks()) {
1924 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001925 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001926 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1927 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1928 }
1929 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001930 }
1931
1932 IntentFilter filter = new IntentFilter();
1933 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1934 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001935 }
1936
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001937 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001938 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001939 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1940 exit();
1941 }
1942 }
1943
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001944 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001945 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001946 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001947 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001948 try {
1949 mContext.unregisterReceiver(mBroadcastReceiver);
1950 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001951 }
1952
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001953 @Override
1954 public void run() {
1955 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001956 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001957 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001958 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001959 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001960 bringup();
1961 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001962 interrupted(); // Clear interrupt flag if execute called exit.
1963 } catch (InterruptedException e) {
1964 } finally {
1965 for (LocalSocket socket : mSockets) {
1966 IoUtils.closeQuietly(socket);
1967 }
1968 // This sleep is necessary for racoon to successfully complete sending delete
1969 // message to server.
1970 try {
1971 Thread.sleep(50);
1972 } catch (InterruptedException e) {
1973 }
1974 for (String daemon : mDaemons) {
1975 SystemService.stop(daemon);
1976 }
1977 }
1978 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001979 }
1980 }
1981
Chalard Jeandd59ece2017-12-20 13:23:32 +09001982 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001983 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09001984 if (now - mBringupStartTime <= 60000) {
1985 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001986 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001987 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09001988 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001989 }
1990 }
1991
Chalard Jeandd59ece2017-12-20 13:23:32 +09001992 private void bringup() {
1993 // Catch all exceptions so we can clean up a few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001994 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001995 try {
1996 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09001997 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001998
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001999 // Wait for the daemons to stop.
2000 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002001 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002002 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002003 }
2004 }
2005
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002006 // Clear the previous state.
2007 File state = new File("/data/misc/vpn/state");
2008 state.delete();
2009 if (state.exists()) {
2010 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002011 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08002012 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002013 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002014
Chia-chi Yehe9107902011-07-02 01:48:50 -07002015 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002016 boolean restart = false;
2017 for (String[] arguments : mArguments) {
2018 restart = restart || (arguments != null);
2019 }
2020 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002021 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002022 return;
2023 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002024 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002025
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002026 // Start the daemon with arguments.
2027 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002028 String[] arguments = mArguments[i];
2029 if (arguments == null) {
2030 continue;
2031 }
2032
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002033 // Start the daemon.
2034 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002035 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002036
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002037 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002038 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09002039 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002040 }
2041
2042 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002043 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002044 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002045 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002046
2047 // Wait for the socket to connect.
2048 while (true) {
2049 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002050 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002051 break;
2052 } catch (Exception e) {
2053 // ignore
2054 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002055 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002056 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002057 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002058
2059 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002060 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002061 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07002062 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002063 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002064 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002065 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002066 out.write(bytes.length >> 8);
2067 out.write(bytes.length);
2068 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002069 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002070 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002071 out.write(0xFF);
2072 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002073 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002074
2075 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002076 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002077 while (true) {
2078 try {
2079 if (in.read() == -1) {
2080 break;
2081 }
2082 } catch (Exception e) {
2083 // ignore
2084 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002085 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002086 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002087 }
2088
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002089 // Wait for the daemons to create the new state.
2090 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002091 // Check if a running daemon is dead.
2092 for (int i = 0; i < mDaemons.length; ++i) {
2093 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002094 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002095 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002096 }
2097 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002098 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002099 }
2100
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002101 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002102 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002103 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002104 throw new IllegalStateException("Cannot parse the state");
2105 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002106
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002107 // Set the interface and the addresses in the config.
2108 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002109
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002110 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002111 // Set the routes if they are not set in the config.
2112 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002113 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002114 }
2115
2116 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002117 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002118 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002119 if (!dnsServers.isEmpty()) {
2120 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2121 }
2122 }
2123
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002124 // Set the search domains if they are not set in the config.
2125 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2126 String searchDomains = parameters[4].trim();
2127 if (!searchDomains.isEmpty()) {
2128 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2129 }
2130 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002131
Lorenzo Colitti50262792014-09-19 01:53:35 +09002132 // Add a throw route for the VPN server endpoint, if one was specified.
2133 String endpoint = parameters[5];
2134 if (!endpoint.isEmpty()) {
2135 try {
2136 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2137 if (addr instanceof Inet4Address) {
2138 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2139 } else if (addr instanceof Inet6Address) {
2140 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2141 } else {
2142 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2143 }
2144 } catch (IllegalArgumentException e) {
2145 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2146 }
2147 }
2148
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002149 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002150 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002151 // Set the start time
2152 mConfig.startTime = SystemClock.elapsedRealtime();
2153
Chalard Jeandd59ece2017-12-20 13:23:32 +09002154 // Check if the thread was interrupted while we were waiting on the lock.
2155 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002156
Chia-chi Yehe9107902011-07-02 01:48:50 -07002157 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002158 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002159 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002160 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002161
2162 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002163 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002164 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002165
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002166 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002167
2168 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002169 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002170 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002171 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002172 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002173 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002174 }
2175 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002176
2177 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002178 * Check all daemons every two seconds. Return when one of them is stopped.
2179 * The caller will move to the disconnected state when this function returns,
2180 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002181 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002182 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002183 if (!mNetworkInfo.isConnected()) {
2184 return;
2185 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002186 while (true) {
2187 Thread.sleep(2000);
2188 for (int i = 0; i < mDaemons.length; i++) {
2189 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2190 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002191 }
2192 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002193 }
2194 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002195 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002196}