blob: dd82950fe0205004d336dc5cc74c3d98479ab1ac [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
Jeff Davidson05542602014-08-11 14:07:27 -0700103import libcore.io.IoUtils;
104
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700105import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700106import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700107import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700108import java.io.OutputStream;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900109import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700110import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700111import java.net.Inet6Address;
112import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700113import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400114import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700115import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100116import java.util.Collection;
117import java.util.Collections;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900118import java.util.Comparator;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400119import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +0100120import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400121import java.util.SortedSet;
122import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700123import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700124
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125/**
126 * @hide
127 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128public class Vpn {
129 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700130 private static final String TAG = "Vpn";
131 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132
Christopher Tatee0be7e82017-02-08 17:38:20 -0800133 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
134 // the device idle whitelist during service launch and VPN bootstrap.
Chalard Jeandd59ece2017-12-20 13:23:32 +0900135 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS = 60 * 1000;
Christopher Tatee0be7e82017-02-08 17:38:20 -0800136
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900137 // Settings for how much of the address space should be routed so that Vpn considers
138 // "most" of the address space is routed. This is used to determine whether this Vpn
139 // should be marked with the INTERNET capability.
140 private static final long MOST_IPV4_ADDRESSES_COUNT;
141 private static final BigInteger MOST_IPV6_ADDRESSES_COUNT;
142 static {
143 // 85% of the address space must be routed for Vpn to consider this VPN to provide
144 // INTERNET access.
145 final int howManyPercentIsMost = 85;
146
147 final long twoPower32 = 1L << 32;
148 MOST_IPV4_ADDRESSES_COUNT = twoPower32 * howManyPercentIsMost / 100;
149 final BigInteger twoPower128 = BigInteger.ONE.shiftLeft(128);
150 MOST_IPV6_ADDRESSES_COUNT = twoPower128
151 .multiply(BigInteger.valueOf(howManyPercentIsMost))
152 .divide(BigInteger.valueOf(100));
153 }
Chalard Jeane0d26f62018-03-29 14:10:44 +0900154 // How many routes to evaluate before bailing and declaring this Vpn should provide
155 // the INTERNET capability. This is necessary because computing the adress space is
156 // O(n²) and this is running in the system service, so a limit is needed to alleviate
157 // the risk of attack.
158 // This is taken as a total of IPv4 + IPV6 routes for simplicity, but the algorithm
159 // is actually O(n²)+O(n²).
160 private static final int MAX_ROUTES_TO_EVALUATE = 150;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create separate trackers for each unique VPN to support
163 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700164
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400165 private Context mContext;
166 private NetworkInfo mNetworkInfo;
167 private String mPackage;
168 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700169 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700170 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700171 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700172 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700173 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400174 private final INetworkManagementService mNetd;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900175 @VisibleForTesting
176 protected VpnConfig mConfig;
177 @VisibleForTesting
178 protected NetworkAgent mNetworkAgent;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400179 private final Looper mLooper;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900180 @VisibleForTesting
181 protected final NetworkCapabilities mNetworkCapabilities;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000182 private final SystemServices mSystemServices;
Chad Brubakerc2865192013-07-10 14:46:23 -0700183
Robin Lee4d03abc2016-05-09 12:32:27 +0100184 /**
Robin Lee17e61832016-05-09 13:46:28 +0100185 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
186 * only applies to {@link VpnService} connections.
187 */
188 private boolean mAlwaysOn = false;
189
190 /**
191 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
192 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
193 * not set.
194 */
195 private boolean mLockdown = false;
196
197 /**
Robin Lee17e61832016-05-09 13:46:28 +0100198 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
199 * when VPN is not running. For example, during system startup or after a crash.
200 * @see mLockdown
201 */
202 @GuardedBy("this")
203 private Set<UidRange> mBlockedUsers = new ArraySet<>();
204
Chalard Jeandd59ece2017-12-20 13:23:32 +0900205 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400206 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207
Chalard Jeandd59ece2017-12-20 13:23:32 +0900208 // Listen to package removal and change events (update/uninstall) for this user
Robin Lee812800c2016-05-13 15:38:08 +0100209 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
210 @Override
211 public void onReceive(Context context, Intent intent) {
212 final Uri data = intent.getData();
213 final String packageName = data == null ? null : data.getSchemeSpecificPart();
214 if (packageName == null) {
215 return;
216 }
217
218 synchronized (Vpn.this) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900219 // Avoid race where always-on package has been unset
Robin Lee812800c2016-05-13 15:38:08 +0100220 if (!packageName.equals(getAlwaysOnPackage())) {
221 return;
222 }
223
224 final String action = intent.getAction();
Chalard Jeandd59ece2017-12-20 13:23:32 +0900225 Log.i(TAG, "Received broadcast " + action + " for always-on VPN package "
226 + packageName + " in user " + mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100227
228 switch(action) {
229 case Intent.ACTION_PACKAGE_REPLACED:
230 // Start vpn after app upgrade
231 startAlwaysOnVpn();
232 break;
233 case Intent.ACTION_PACKAGE_REMOVED:
234 final boolean isPackageRemoved = !intent.getBooleanExtra(
235 Intent.EXTRA_REPLACING, false);
236 if (isPackageRemoved) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000237 setAlwaysOnPackage(null, false);
Robin Lee812800c2016-05-13 15:38:08 +0100238 }
239 break;
240 }
241 }
242 }
243 };
244
245 private boolean mIsPackageIntentReceiverRegistered = false;
246
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400247 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000248 @UserIdInt int userHandle) {
249 this(looper, context, netService, userHandle, new SystemServices(context));
250 }
251
252 @VisibleForTesting
253 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
254 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700255 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400256 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400257 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400258 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000259 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400260
261 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400262 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700263
264 try {
265 netService.registerObserver(mObserver);
266 } catch (RemoteException e) {
267 Log.wtf(TAG, "Problem registering observer", e);
268 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400269
Chalard Jeandd59ece2017-12-20 13:23:32 +0900270 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
271 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400272 mNetworkCapabilities = new NetworkCapabilities();
273 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
274 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600275 updateCapabilities();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000276
277 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700278 }
279
Jeff Sharkey57666932013-04-30 17:01:57 -0700280 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900281 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700282 * teardown. When {@code false}, teardown is handled externally by someone
283 * else.
284 */
285 public void setEnableTeardown(boolean enableTeardown) {
286 mEnableTeardown = enableTeardown;
287 }
288
Jeff Sharkey899223b2012-08-04 15:24:58 -0700289 /**
290 * Update current state, dispaching event to listeners.
291 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100292 @VisibleForTesting
293 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700294 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
295 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400296 if (mNetworkAgent != null) {
297 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
298 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100299 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700300 }
301
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600302 public void updateCapabilities() {
303 final Network[] underlyingNetworks = (mConfig != null) ? mConfig.underlyingNetworks : null;
304 updateCapabilities(mContext.getSystemService(ConnectivityManager.class), underlyingNetworks,
305 mNetworkCapabilities);
306
307 if (mNetworkAgent != null) {
308 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
309 }
310 }
311
312 @VisibleForTesting
313 public static void updateCapabilities(ConnectivityManager cm, Network[] underlyingNetworks,
314 NetworkCapabilities caps) {
315 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
316 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
317 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
318 boolean metered = false;
319 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900320 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600321
322 if (ArrayUtils.isEmpty(underlyingNetworks)) {
323 // No idea what the underlying networks are; assume sane defaults
324 metered = true;
325 roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900326 congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600327 } else {
328 for (Network underlying : underlyingNetworks) {
329 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700330 if (underlyingCaps == null) continue;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600331 for (int underlyingType : underlyingCaps.getTransportTypes()) {
332 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
333 }
334
335 // When we have multiple networks, we have to assume the
336 // worst-case link speed and restrictions.
337 downKbps = NetworkCapabilities.minBandwidth(downKbps,
338 underlyingCaps.getLinkDownstreamBandwidthKbps());
339 upKbps = NetworkCapabilities.minBandwidth(upKbps,
340 underlyingCaps.getLinkUpstreamBandwidthKbps());
341 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
342 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900343 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600344 }
345 }
346
347 caps.setTransportTypes(transportTypes);
348 caps.setLinkDownstreamBandwidthKbps(downKbps);
349 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900350 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
351 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
352 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600353 }
354
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700355 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000356 * Chooses whether to force all connections to go though VPN.
357 *
358 * Used to enable/disable legacy VPN lockdown.
359 *
360 * This uses the same ip rule mechanism as {@link #setAlwaysOnPackage(String, boolean)};
361 * previous settings from calling that function will be replaced and saved with the
362 * always-on state.
363 *
364 * @param lockdown whether to prevent all traffic outside of a VPN.
365 */
366 public synchronized void setLockdown(boolean lockdown) {
367 enforceControlPermissionOrInternalCaller();
368
369 setVpnForcedLocked(lockdown);
370 mLockdown = lockdown;
371
372 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
373 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
374 if (mAlwaysOn) {
375 saveAlwaysOnPackage();
376 }
377 }
378
379 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100380 * Checks if a VPN app supports always-on mode.
381 *
382 * In order to support the always-on feature, an app has to
383 * <ul>
384 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100385 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
386 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100387 * </ul>
388 *
389 * @param packageName the canonical package name of the VPN app
390 * @return {@code true} if and only if the VPN app exists and supports always-on mode
391 */
392 public boolean isAlwaysOnPackageSupported(String packageName) {
393 enforceSettingsPermission();
394
395 if (packageName == null) {
396 return false;
397 }
398
399 PackageManager pm = mContext.getPackageManager();
400 ApplicationInfo appInfo = null;
401 try {
402 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
403 } catch (NameNotFoundException unused) {
404 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
405 }
406 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
407 return false;
408 }
409
410 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
411 intent.setPackage(packageName);
412 List<ResolveInfo> services =
413 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
414 if (services == null || services.size() == 0) {
415 return false;
416 }
417
418 for (ResolveInfo rInfo : services) {
419 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100420 if (metaData != null &&
421 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100422 return false;
423 }
424 }
425
426 return true;
427 }
428
429 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000430 * Configures an always-on VPN connection through a specific application.
431 * This connection is automatically granted and persisted after a reboot.
432 *
433 * <p>The designated package should exist and declare a {@link VpnService} in its
434 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
435 * otherwise the call will fail.
436 *
Charles Hea0a87e82017-05-15 17:07:18 +0100437 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
438 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
439 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
440 *
Robin Lee17e61832016-05-09 13:46:28 +0100441 * @param packageName the package to designate as always-on VPN supplier.
442 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100443 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000444 */
Robin Lee17e61832016-05-09 13:46:28 +0100445 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000446 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000447
448 if (setAlwaysOnPackageInternal(packageName, lockdown)) {
449 saveAlwaysOnPackage();
450 return true;
451 }
452 return false;
453 }
454
455 /**
456 * Configures an always-on VPN connection through a specific application, the same as
457 * {@link #setAlwaysOnPackage}.
458 *
459 * Does not perform permission checks. Does not persist any of the changes to storage.
460 *
461 * @param packageName the package to designate as always-on VPN supplier.
462 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
463 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
464 */
465 @GuardedBy("this")
466 private boolean setAlwaysOnPackageInternal(String packageName, boolean lockdown) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100467 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
468 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
469 return false;
470 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000471
Robin Lee244ce8e2016-01-05 18:03:46 +0000472 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100473 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000474 if (!setPackageAuthorization(packageName, true)) {
475 return false;
476 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100477 mAlwaysOn = true;
478 } else {
479 packageName = VpnConfig.LEGACY_VPN;
480 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000481 }
482
Robin Lee17e61832016-05-09 13:46:28 +0100483 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100484 if (isCurrentPreparedPackage(packageName)) {
485 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
486 } else {
487 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100488 prepareInternal(packageName);
489 }
Robin Lee812800c2016-05-13 15:38:08 +0100490 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100491 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000492 return true;
493 }
494
Robin Lee9ff1a582016-06-10 16:41:10 +0100495 private static boolean isNullOrLegacyVpn(String packageName) {
496 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
497 }
498
Robin Lee812800c2016-05-13 15:38:08 +0100499 private void unregisterPackageChangeReceiverLocked() {
Robin Lee812800c2016-05-13 15:38:08 +0100500 if (mIsPackageIntentReceiverRegistered) {
501 mContext.unregisterReceiver(mPackageIntentReceiver);
502 mIsPackageIntentReceiverRegistered = false;
503 }
504 }
505
506 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
507 // Unregister IntentFilter listening for previous always-on package change
508 unregisterPackageChangeReceiverLocked();
509
Robin Lee9ff1a582016-06-10 16:41:10 +0100510 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100511 mIsPackageIntentReceiverRegistered = true;
512
513 IntentFilter intentFilter = new IntentFilter();
514 // Protected intent can only be sent by system. No permission required in register.
515 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
516 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
517 intentFilter.addDataScheme("package");
518 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
519 mContext.registerReceiverAsUser(
520 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
521 }
522 }
523
Robin Lee244ce8e2016-01-05 18:03:46 +0000524 /**
525 * @return the package name of the VPN controller responsible for always-on VPN,
526 * or {@code null} if none is set or always-on VPN is controlled through
527 * lockdown instead.
528 * @hide
529 */
530 public synchronized String getAlwaysOnPackage() {
531 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100532 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000533 }
534
535 /**
Robin Lee812800c2016-05-13 15:38:08 +0100536 * Save the always-on package and lockdown config into Settings.Secure
537 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000538 @GuardedBy("this")
539 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100540 final long token = Binder.clearCallingIdentity();
541 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000542 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100543 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000544 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000545 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100546 } finally {
547 Binder.restoreCallingIdentity(token);
548 }
549 }
550
551 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000552 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100553 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000554 @GuardedBy("this")
555 private void loadAlwaysOnPackage() {
556 final long token = Binder.clearCallingIdentity();
557 try {
558 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
559 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
560 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
561 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
562 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown);
563 } finally {
564 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100565 }
566 }
567
568 /**
569 * @return {@code true} if the service was started, the service was already connected, or there
570 * was no always-on VPN to start. {@code false} otherwise.
571 */
572 public boolean startAlwaysOnVpn() {
573 final String alwaysOnPackage;
574 synchronized (this) {
575 alwaysOnPackage = getAlwaysOnPackage();
576 // Skip if there is no service to start.
577 if (alwaysOnPackage == null) {
578 return true;
579 }
Charles Hea0a87e82017-05-15 17:07:18 +0100580 // Remove always-on VPN if it's not supported.
581 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
582 setAlwaysOnPackage(null, false);
583 return false;
584 }
Robin Lee812800c2016-05-13 15:38:08 +0100585 // Skip if the service is already established. This isn't bulletproof: it's not bound
586 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
587 // which may restart the connection.
588 if (getNetworkInfo().isConnected()) {
589 return true;
590 }
591 }
592
Christopher Tatee0be7e82017-02-08 17:38:20 -0800593 // Tell the OS that background services in this app need to be allowed for
594 // a short time, so we can bootstrap the VPN service.
595 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100596 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800597 DeviceIdleController.LocalService idleController =
598 LocalServices.getService(DeviceIdleController.LocalService.class);
599 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900600 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800601
602 // Start the VPN service declared in the app's manifest.
603 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
604 serviceIntent.setPackage(alwaysOnPackage);
605 try {
606 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
607 } catch (RuntimeException e) {
608 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
609 return false;
610 }
611 } finally {
612 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100613 }
614 }
615
616 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700617 * Prepare for a VPN application. This method is designed to solve
618 * race conditions. It first compares the current prepared package
619 * with {@code oldPackage}. If they are the same, the prepared
620 * package is revoked and replaced with {@code newPackage}. If
621 * {@code oldPackage} is {@code null}, the comparison is omitted.
622 * If {@code newPackage} is the same package or {@code null}, the
623 * revocation is omitted. This method returns {@code true} if the
624 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700625 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700626 * Legacy VPN is handled specially since it is not a real package.
627 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
628 * it can be revoked by itself.
629 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900630 * Note: when we added VPN pre-consent in
631 * https://android.googlesource.com/platform/frameworks/base/+/0554260
632 * the names oldPackage and newPackage became misleading, because when
633 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100634 *
635 * Their meanings actually are:
636 *
637 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
638 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100639 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100640 * and revoke any current app VPN and re-prepare legacy vpn.
641 *
Robin Lee812800c2016-05-13 15:38:08 +0100642 * TODO: Rename the variables - or split this method into two - and end this confusion.
643 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
644 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100645 *
646 * @param oldPackage The package name of the old VPN application
647 * @param newPackage The package name of the new VPN application
648 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900649 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700650 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700651 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700652 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100653 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100654 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100655 return false;
656 }
657
Chalard Jeandd59ece2017-12-20 13:23:32 +0900658 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100659 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700660 // The package doesn't match. We return false (to obtain user consent) unless the
661 // user has already consented to that VPN package.
662 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
663 prepareInternal(oldPackage);
664 return true;
665 }
666 return false;
667 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
668 && !isVpnUserPreConsented(oldPackage)) {
669 // Currently prepared VPN is revoked, so unprepare it and return false.
670 prepareInternal(VpnConfig.LEGACY_VPN);
671 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700672 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700673 }
674
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700675 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700676 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100677 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700678 return true;
679 }
680
Robin Lee1b1bcd72016-02-12 18:11:30 +0000681 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700682 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700683
Victor Chang98a633a2016-05-27 17:30:49 +0100684 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100685 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100686 return false;
687 }
688
Jeff Davidson11008a72014-11-20 13:12:46 -0800689 prepareInternal(newPackage);
690 return true;
691 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700692
Victor Chang98a633a2016-05-27 17:30:49 +0100693 private boolean isCurrentPreparedPackage(String packageName) {
694 // We can't just check that packageName matches mPackage, because if the app was uninstalled
695 // and reinstalled it will no longer be prepared. Instead check the UID.
696 return getAppUid(packageName, mUserHandle) == mOwnerUID;
697 }
698
Jeff Davidson11008a72014-11-20 13:12:46 -0800699 /** Prepare the VPN for the given package. Does not perform permission checks. */
700 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400701 long token = Binder.clearCallingIdentity();
702 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800703 // Reset the interface.
704 if (mInterface != null) {
705 mStatusIntent = null;
706 agentDisconnect();
707 jniReset(mInterface);
708 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900709 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800710 }
711
712 // Revoke the connection or stop LegacyVpnRunner.
713 if (mConnection != null) {
714 try {
715 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
716 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
717 } catch (Exception e) {
718 // ignore
719 }
720 mContext.unbindService(mConnection);
721 mConnection = null;
722 } else if (mLegacyVpnRunner != null) {
723 mLegacyVpnRunner.exit();
724 mLegacyVpnRunner = null;
725 }
726
727 try {
728 mNetd.denyProtect(mOwnerUID);
729 } catch (Exception e) {
730 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
731 }
732
733 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
734 mPackage = newPackage;
735 mOwnerUID = getAppUid(newPackage, mUserHandle);
736 try {
737 mNetd.allowProtect(mOwnerUID);
738 } catch (Exception e) {
739 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
740 }
741 mConfig = null;
742
743 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000744 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400745 } finally {
746 Binder.restoreCallingIdentity(token);
747 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700748 }
749
Jeff Davidson05542602014-08-11 14:07:27 -0700750 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100751 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700752 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000753 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700754 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000755 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700756
Robin Lee3b3dd942015-05-12 18:14:58 +0100757 int uid = getAppUid(packageName, mUserHandle);
758 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
759 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000760 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700761 }
762
763 long token = Binder.clearCallingIdentity();
764 try {
765 AppOpsManager appOps =
766 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100767 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700768 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000769 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700770 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100771 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700772 } finally {
773 Binder.restoreCallingIdentity(token);
774 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000775 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700776 }
777
778 private boolean isVpnUserPreConsented(String packageName) {
779 AppOpsManager appOps =
780 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
781
782 // Verify that the caller matches the given package and has permission to activate VPNs.
783 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
784 packageName) == AppOpsManager.MODE_ALLOWED;
785 }
786
Paul Jensen0784eea2014-08-19 16:00:24 -0400787 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700788 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400789 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700790 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400791 PackageManager pm = mContext.getPackageManager();
792 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700793 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700794 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400795 } catch (NameNotFoundException e) {
796 result = -1;
797 }
798 return result;
799 }
800
801 public NetworkInfo getNetworkInfo() {
802 return mNetworkInfo;
803 }
804
Paul Jensen31a94f42015-02-13 14:18:39 -0500805 public int getNetId() {
806 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
807 }
808
Lorenzo Colitti60446162014-09-20 00:14:31 +0900809 private LinkProperties makeLinkProperties() {
810 boolean allowIPv4 = mConfig.allowIPv4;
811 boolean allowIPv6 = mConfig.allowIPv6;
812
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400813 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900814
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400815 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700816
Lorenzo Colitti60446162014-09-20 00:14:31 +0900817 if (mConfig.addresses != null) {
818 for (LinkAddress address : mConfig.addresses) {
819 lp.addLinkAddress(address);
820 allowIPv4 |= address.getAddress() instanceof Inet4Address;
821 allowIPv6 |= address.getAddress() instanceof Inet6Address;
822 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400823 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900824
825 if (mConfig.routes != null) {
826 for (RouteInfo route : mConfig.routes) {
827 lp.addRoute(route);
828 InetAddress address = route.getDestination().getAddress();
829 allowIPv4 |= address instanceof Inet4Address;
830 allowIPv6 |= address instanceof Inet6Address;
831 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400832 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700833
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400834 if (mConfig.dnsServers != null) {
835 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700836 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
837 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900838 allowIPv4 |= address instanceof Inet4Address;
839 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400840 }
841 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700842
Lorenzo Colitti60446162014-09-20 00:14:31 +0900843 if (!allowIPv4) {
844 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
845 }
846 if (!allowIPv6) {
847 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
848 }
849
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400850 // Concatenate search domains into a string.
851 StringBuilder buffer = new StringBuilder();
852 if (mConfig.searchDomains != null) {
853 for (String domain : mConfig.searchDomains) {
854 buffer.append(domain).append(' ');
855 }
856 }
857 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700858
Lorenzo Colitti60446162014-09-20 00:14:31 +0900859 // TODO: Stop setting the MTU in jniCreate and set it here.
860
861 return lp;
862 }
863
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900864 /**
865 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
866 *
867 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
868 * space or to most of the IPv6 address space, where "most" is defined by the value of the
869 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
870 * by any of the routes, then it's decided that most of the space is routed.
871 * @hide
872 */
873 @VisibleForTesting
874 static boolean providesRoutesToMostDestinations(LinkProperties lp) {
Chalard Jeane0d26f62018-03-29 14:10:44 +0900875 final List<RouteInfo> routes = lp.getAllRoutes();
876 if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900877 final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
878 TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
879 TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
Chalard Jeane0d26f62018-03-29 14:10:44 +0900880 for (final RouteInfo route : routes) {
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900881 IpPrefix destination = route.getDestination();
882 if (destination.isIPv4()) {
883 ipv4Prefixes.add(destination);
884 } else {
885 ipv6Prefixes.add(destination);
886 }
887 }
888 if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
889 return true;
890 }
891 return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
892 .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
893 }
894
Lorenzo Colitti60446162014-09-20 00:14:31 +0900895 private void agentConnect() {
896 LinkProperties lp = makeLinkProperties();
897
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900898 if (providesRoutesToMostDestinations(lp)) {
Lorenzo Colitti60446162014-09-20 00:14:31 +0900899 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
900 } else {
901 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
902 }
903
Robin Lee323f29d2016-05-04 16:38:06 +0100904 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700905
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700906 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100907 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700908
Chalard Jeanf474fc32018-01-17 15:10:05 +0900909 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900910 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
911 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400912 long token = Binder.clearCallingIdentity();
913 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900914 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900915 mNetworkInfo, mNetworkCapabilities, lp,
916 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700917 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400918 public void unwanted() {
919 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700920 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400921 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700922 } finally {
923 Binder.restoreCallingIdentity(token);
924 }
Robin Lee323f29d2016-05-04 16:38:06 +0100925 mNetworkInfo.setIsAvailable(true);
926 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400927 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700928
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700929 private boolean canHaveRestrictedProfile(int userId) {
930 long token = Binder.clearCallingIdentity();
931 try {
932 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
933 } finally {
934 Binder.restoreCallingIdentity(token);
935 }
936 }
937
Tony Mak1a405fe2016-06-30 11:19:20 +0100938 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400939 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100940 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
941 networkInfo.setIsAvailable(false);
942 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400943 networkAgent.sendNetworkInfo(networkInfo);
944 }
945 }
946
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400947 private void agentDisconnect() {
948 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100949 mNetworkInfo.setIsAvailable(false);
950 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400951 mNetworkAgent = null;
952 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700953 }
954
955 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700956 * Establish a VPN network and return the file descriptor of the VPN
957 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700958 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700959 *
960 * @param config The parameters to configure the network.
961 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700962 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700963 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700964 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700965 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400966 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700967 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700968 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700969 // Check to ensure consent hasn't been revoked since we were prepared.
970 if (!isVpnUserPreConsented(mPackage)) {
971 return null;
972 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700973 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700974 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
975 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700976 long token = Binder.clearCallingIdentity();
977 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700978 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400979 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100980 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700981 throw new SecurityException("Restricted users cannot establish VPNs");
982 }
983
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700984 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900985 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700986 if (info == null) {
987 throw new SecurityException("Cannot find " + config.user);
988 }
989 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
990 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
991 }
992 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900993 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700994 } finally {
995 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700996 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700997
Chad Brubaker850eb672014-03-21 21:02:47 +0000998 // Save the old config in case we need to go back.
999 VpnConfig oldConfig = mConfig;
1000 String oldInterface = mInterface;
1001 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001002 NetworkAgent oldNetworkAgent = mNetworkAgent;
1003 mNetworkAgent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001004 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +00001005
Chia-chi Yehe9107902011-07-02 01:48:50 -07001006 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001007 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001008 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001009 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001010 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001011
Chad Brubakerc2865192013-07-10 14:46:23 -07001012 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001013 StringBuilder builder = new StringBuilder();
1014 for (LinkAddress address : config.addresses) {
1015 builder.append(" " + address);
1016 }
1017 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001018 throw new IllegalArgumentException("At least one address must be specified");
1019 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001020 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001021 if (!mContext.bindServiceAsUser(intent, connection,
1022 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1023 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001024 throw new IllegalStateException("Cannot bind " + config.user);
1025 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001026
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001027 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001028 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001029
1030 // Fill more values.
1031 config.user = mPackage;
1032 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001033 config.startTime = SystemClock.elapsedRealtime();
1034 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001035
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001036 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001037 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001038
1039 if (oldConnection != null) {
1040 mContext.unbindService(oldConnection);
1041 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001042 // Remove the old tun's user forwarding rules
1043 // The new tun's user rules have already been added so they will take over
1044 // as rules are deleted. This prevents data leakage as the rules are moved over.
1045 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +00001046 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001047 jniReset(oldInterface);
1048 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001049
1050 try {
1051 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1052 } catch (IOException e) {
1053 throw new IllegalStateException(
1054 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1055 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001056 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001057 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001058 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001059 // restore old state
1060 mConfig = oldConfig;
1061 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001062 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001063 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001064 mInterface = oldInterface;
1065 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001066 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001067 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001068 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001069 }
1070
Chad Brubakerc2865192013-07-10 14:46:23 -07001071 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001072 return mNetworkAgent != null && mInterface != null;
1073 }
1074
1075 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1076 // that a call to mutate VPN state is admissible.
Chalard Jeanf666d0a2018-05-18 21:47:45 +09001077 @VisibleForTesting
1078 protected boolean isCallerEstablishedOwnerLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001079 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001080 }
1081
Paul Jensen0784eea2014-08-19 16:00:24 -04001082 // Note: Return type guarantees results are deduped and sorted, which callers require.
1083 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
1084 SortedSet<Integer> uids = new TreeSet<Integer>();
1085 for (String app : packageNames) {
1086 int uid = getAppUid(app, userHandle);
1087 if (uid != -1) uids.add(uid);
1088 }
1089 return uids;
1090 }
1091
Robin Lee4d03abc2016-05-09 12:32:27 +01001092 /**
1093 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1094 * associated with one user, and any restricted profiles attached to that user.
1095 *
1096 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1097 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1098 * in each user and profile will be included.
1099 *
1100 * @param userHandle The userId to create UID ranges for along with any of its restricted
1101 * profiles.
1102 * @param allowedApplications (optional) whitelist of applications to include.
1103 * @param disallowedApplications (optional) blacklist of applications to exclude.
1104 */
1105 @VisibleForTesting
1106 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1107 @Nullable List<String> allowedApplications,
1108 @Nullable List<String> disallowedApplications) {
1109 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001110
Robin Lee4d03abc2016-05-09 12:32:27 +01001111 // Assign the top-level user to the set of ranges
1112 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1113
1114 // If the user can have restricted profiles, assign all its restricted profiles too
1115 if (canHaveRestrictedProfile(userHandle)) {
1116 final long token = Binder.clearCallingIdentity();
1117 List<UserInfo> users;
1118 try {
Robin Lee17e61832016-05-09 13:46:28 +01001119 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001120 } finally {
1121 Binder.restoreCallingIdentity(token);
1122 }
1123 for (UserInfo user : users) {
1124 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1125 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1126 }
1127 }
1128 }
1129 return ranges;
1130 }
1131
1132 /**
1133 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1134 * associated with one user.
1135 *
1136 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1137 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1138 * in the user will be included.
1139 *
1140 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1141 * @param userHandle The userId to add to {@param ranges}.
1142 * @param allowedApplications (optional) whitelist of applications to include.
1143 * @param disallowedApplications (optional) blacklist of applications to exclude.
1144 */
1145 @VisibleForTesting
1146 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1147 @Nullable List<String> allowedApplications,
1148 @Nullable List<String> disallowedApplications) {
1149 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001150 // Add ranges covering all UIDs for allowedApplications.
1151 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001152 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001153 if (start == -1) {
1154 start = uid;
1155 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001156 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001157 start = uid;
1158 }
1159 stop = uid;
1160 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001161 if (start != -1) ranges.add(new UidRange(start, stop));
1162 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001163 // Add all ranges for user skipping UIDs for disallowedApplications.
1164 final UidRange userRange = UidRange.createForUser(userHandle);
1165 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001166 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001167 if (uid == start) {
1168 start++;
1169 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001170 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001171 start = uid + 1;
1172 }
1173 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001174 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001175 } else {
1176 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001177 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001178 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001179 }
1180
Paul Jensen0784eea2014-08-19 16:00:24 -04001181 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1182 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001183 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1184 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1185 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001186 final UidRange userRange = UidRange.createForUser(userHandle);
1187 final List<UidRange> ranges = new ArrayList<UidRange>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001188 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001189 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001190 ranges.add(range);
1191 }
1192 }
1193 return ranges;
1194 }
1195
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001196 public void onUserAdded(int userHandle) {
1197 // If the user is restricted tie them to the parent user's VPN
1198 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001199 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001200 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001201 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1202 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001203 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001204 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001205 mConfig.disallowedApplications);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001206 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001207 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001208 } catch (Exception e) {
1209 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001210 }
Robin Lee17e61832016-05-09 13:46:28 +01001211 }
Robin Leec3736bc2017-03-10 16:19:54 +00001212 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001213 }
1214 }
1215 }
1216
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001217 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001218 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001219 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001220 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001221 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001222 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1223 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001224 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001225 final List<UidRange> removedRanges =
1226 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001227 existingRanges.removeAll(removedRanges);
1228 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001229 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001230 } catch (Exception e) {
1231 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1232 }
1233 }
Robin Leec3736bc2017-03-10 16:19:54 +00001234 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001235 }
1236 }
1237 }
1238
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001239 /**
Robin Lee17e61832016-05-09 13:46:28 +01001240 * Called when the user associated with this VPN has just been stopped.
1241 */
1242 public synchronized void onUserStopped() {
1243 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001244 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001245 mAlwaysOn = false;
1246
Robin Lee812800c2016-05-13 15:38:08 +01001247 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001248 // Quit any active connections
1249 agentDisconnect();
1250 }
1251
1252 /**
1253 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1254 * service app itself, to only sockets that have had {@code protect()} called on them. All
1255 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1256 *
1257 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1258 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1259 *
1260 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1261 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1262 *
1263 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1264 * {@link Vpn} goes through a VPN connection or is blocked until one is
1265 * available, {@code false} to lift the requirement.
1266 *
1267 * @see #mBlockedUsers
1268 */
1269 @GuardedBy("this")
1270 private void setVpnForcedLocked(boolean enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001271 final List<String> exemptedPackages =
1272 isNullOrLegacyVpn(mPackage) ? null : Collections.singletonList(mPackage);
Robin Lee17e61832016-05-09 13:46:28 +01001273 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
Robin Leec3736bc2017-03-10 16:19:54 +00001274
1275 Set<UidRange> addedRanges = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001276 if (enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001277 addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
Robin Lee17e61832016-05-09 13:46:28 +01001278 /* allowedApplications */ null,
Robin Leec3736bc2017-03-10 16:19:54 +00001279 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001280
1281 removedRanges.removeAll(addedRanges);
1282 addedRanges.removeAll(mBlockedUsers);
Robin Lee17e61832016-05-09 13:46:28 +01001283 }
Robin Leec3736bc2017-03-10 16:19:54 +00001284
1285 setAllowOnlyVpnForUids(false, removedRanges);
1286 setAllowOnlyVpnForUids(true, addedRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001287 }
1288
1289 /**
1290 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1291 * to make connections through sockets that have had {@code protect()} called on them.
1292 *
1293 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1294 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1295 * {@code true}) or to remove.
1296 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1297 * including added ranges that already existed or removed ones that didn't.
1298 */
1299 @GuardedBy("this")
1300 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1301 if (ranges.size() == 0) {
1302 return true;
1303 }
1304 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1305 try {
1306 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1307 } catch (RemoteException | RuntimeException e) {
1308 Log.e(TAG, "Updating blocked=" + enforce
1309 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1310 return false;
1311 }
1312 if (enforce) {
1313 mBlockedUsers.addAll(ranges);
1314 } else {
1315 mBlockedUsers.removeAll(ranges);
1316 }
1317 return true;
1318 }
1319
1320 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001321 * Return the configuration of the currently running VPN.
1322 */
1323 public VpnConfig getVpnConfig() {
1324 enforceControlPermission();
1325 return mConfig;
1326 }
1327
Jeff Sharkey899223b2012-08-04 15:24:58 -07001328 @Deprecated
1329 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1330 try {
1331 mObserver.interfaceStatusChanged(iface, up);
1332 } catch (RemoteException e) {
1333 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001334 }
1335 }
1336
Jeff Sharkey899223b2012-08-04 15:24:58 -07001337 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1338 @Override
1339 public void interfaceStatusChanged(String interfaze, boolean up) {
1340 synchronized (Vpn.this) {
1341 if (!up && mLegacyVpnRunner != null) {
1342 mLegacyVpnRunner.check(interfaze);
1343 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001344 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001345 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001346
Jeff Sharkey899223b2012-08-04 15:24:58 -07001347 @Override
1348 public void interfaceRemoved(String interfaze) {
1349 synchronized (Vpn.this) {
1350 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001351 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001352 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001353 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001354 mInterface = null;
1355 if (mConnection != null) {
1356 mContext.unbindService(mConnection);
1357 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001358 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001359 } else if (mLegacyVpnRunner != null) {
1360 mLegacyVpnRunner.exit();
1361 mLegacyVpnRunner = null;
1362 }
1363 }
1364 }
1365 }
1366 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001367
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001368 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001369 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001370 }
1371
Robin Lee244ce8e2016-01-05 18:03:46 +00001372 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001373 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001374 // in the system server.
1375 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1376 "Unauthorized Caller");
1377 }
1378
Charles Hea0a87e82017-05-15 17:07:18 +01001379 private void enforceSettingsPermission() {
1380 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1381 "Unauthorized Caller");
1382 }
1383
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001384 private class Connection implements ServiceConnection {
1385 private IBinder mService;
1386
1387 @Override
1388 public void onServiceConnected(ComponentName name, IBinder service) {
1389 mService = service;
1390 }
1391
1392 @Override
1393 public void onServiceDisconnected(ComponentName name) {
1394 mService = null;
1395 }
1396 }
1397
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001398 private void prepareStatusIntent() {
1399 final long token = Binder.clearCallingIdentity();
1400 try {
1401 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1402 } finally {
1403 Binder.restoreCallingIdentity(token);
1404 }
1405 }
1406
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001407 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001408 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001409 return false;
1410 }
1411 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001412 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001413 return success;
1414 }
1415
1416 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001417 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001418 return false;
1419 }
1420 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001421 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001422 return success;
1423 }
1424
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001425 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1426 if (!isCallerEstablishedOwnerLocked()) {
1427 return false;
1428 }
1429 if (networks == null) {
1430 mConfig.underlyingNetworks = null;
1431 } else {
1432 mConfig.underlyingNetworks = new Network[networks.length];
1433 for (int i = 0; i < networks.length; ++i) {
1434 if (networks[i] == null) {
1435 mConfig.underlyingNetworks[i] = null;
1436 } else {
1437 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1438 }
1439 }
1440 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001441 updateCapabilities();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001442 return true;
1443 }
1444
1445 public synchronized Network[] getUnderlyingNetworks() {
1446 if (!isRunningLocked()) {
1447 return null;
1448 }
1449 return mConfig.underlyingNetworks;
1450 }
1451
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001452 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001453 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001454 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1455 */
1456 public synchronized VpnInfo getVpnInfo() {
1457 if (!isRunningLocked()) {
1458 return null;
1459 }
1460
1461 VpnInfo info = new VpnInfo();
1462 info.ownerUid = mOwnerUID;
1463 info.vpnIface = mInterface;
1464 return info;
1465 }
1466
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001467 public synchronized boolean appliesToUid(int uid) {
1468 if (!isRunningLocked()) {
1469 return false;
1470 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001471 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001472 }
1473
Robin Lee17e61832016-05-09 13:46:28 +01001474 /**
Robin Leeebbcb542016-05-24 16:35:10 +01001475 * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1476 * A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1477 * not connected, or if the VPN is connected but does not apply to the UID.
Robin Lee17e61832016-05-09 13:46:28 +01001478 *
1479 * @see #mBlockedUsers
1480 */
1481 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001482 if (!mLockdown) {
1483 return false;
Robin Lee17e61832016-05-09 13:46:28 +01001484 }
Robin Leeebbcb542016-05-24 16:35:10 +01001485
1486 if (mNetworkInfo.isConnected()) {
1487 return !appliesToUid(uid);
1488 } else {
1489 for (UidRange uidRange : mBlockedUsers) {
1490 if (uidRange.contains(uid)) {
1491 return true;
1492 }
1493 }
1494 return false;
1495 }
Robin Lee17e61832016-05-09 13:46:28 +01001496 }
1497
Tony Mak1a405fe2016-06-30 11:19:20 +01001498 private void updateAlwaysOnNotification(DetailedState networkState) {
1499 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001500
Tony Mak1a405fe2016-06-30 11:19:20 +01001501 final UserHandle user = UserHandle.of(mUserHandle);
1502 final long token = Binder.clearCallingIdentity();
1503 try {
1504 final NotificationManager notificationManager = NotificationManager.from(mContext);
1505 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001506 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001507 return;
1508 }
Charles Heab6f2f62017-07-12 15:30:00 +01001509 final Intent intent = new Intent();
1510 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1511 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1512 intent.putExtra("lockdown", mLockdown);
1513 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001514 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1515 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001516 final Notification.Builder builder =
1517 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1518 .setSmallIcon(R.drawable.vpn_connected)
1519 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1520 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1521 .setContentIntent(configIntent)
1522 .setCategory(Notification.CATEGORY_SYSTEM)
1523 .setVisibility(Notification.VISIBILITY_PUBLIC)
1524 .setOngoing(true)
1525 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001526 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1527 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001528 } finally {
1529 Binder.restoreCallingIdentity(token);
1530 }
1531 }
1532
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001533 /**
1534 * Facade for system service calls that change, or depend on, state outside of
1535 * {@link ConnectivityService} and have hard-to-mock interfaces.
1536 *
1537 * @see com.android.server.connectivity.VpnTest
1538 */
1539 @VisibleForTesting
1540 public static class SystemServices {
1541 private final Context mContext;
1542
1543 public SystemServices(@NonNull Context context) {
1544 mContext = context;
1545 }
1546
1547 /**
1548 * @see PendingIntent#getActivityAsUser()
1549 */
1550 public PendingIntent pendingIntentGetActivityAsUser(
1551 Intent intent, int flags, UserHandle user) {
1552 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1553 null /*options*/, user);
1554 }
1555
1556 /**
1557 * @see Settings.Secure#putStringForUser
1558 */
1559 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1560 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1561 }
1562
1563 /**
1564 * @see Settings.Secure#putIntForUser
1565 */
1566 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1567 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1568 }
1569
1570 /**
1571 * @see Settings.Secure#getStringForUser
1572 */
1573 public String settingsSecureGetStringForUser(String key, int userId) {
1574 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1575 }
1576
1577 /**
1578 * @see Settings.Secure#getIntForUser
1579 */
1580 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1581 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1582 }
1583 }
1584
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001585 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001586 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001587 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001588 private native void jniReset(String interfaze);
1589 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001590 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1591 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001592
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001593 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1594 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001595 // Currently legacy VPN only works on IPv4.
1596 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001597 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001598 }
1599 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001600
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001601 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001602 }
1603
1604 /**
1605 * Start legacy VPN, controlling native daemons as needed. Creates a
1606 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001607 *
1608 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1609 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1610 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001611 */
1612 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001613 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001614 long token = Binder.clearCallingIdentity();
1615 try {
1616 startLegacyVpnPrivileged(profile, keyStore, egress);
1617 } finally {
1618 Binder.restoreCallingIdentity(token);
1619 }
1620 }
1621
1622 /**
1623 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1624 * permissions under the assumption that the caller is the system.
1625 *
1626 * Callers are responsible for checking permissions if needed.
1627 */
1628 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1629 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001630 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001631 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001632 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1633 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001634 throw new SecurityException("Restricted users cannot establish VPNs");
1635 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001636
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001637 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1638 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1639 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001640
1641 // Load certificates.
1642 String privateKey = "";
1643 String userCert = "";
1644 String caCert = "";
1645 String serverCert = "";
1646 if (!profile.ipsecUserCert.isEmpty()) {
1647 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1648 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001649 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001650 }
1651 if (!profile.ipsecCaCert.isEmpty()) {
1652 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001653 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001654 }
1655 if (!profile.ipsecServerCert.isEmpty()) {
1656 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001657 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001658 }
1659 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1660 throw new IllegalStateException("Cannot load credentials");
1661 }
1662
1663 // Prepare arguments for racoon.
1664 String[] racoon = null;
1665 switch (profile.type) {
1666 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1667 racoon = new String[] {
1668 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1669 profile.ipsecSecret, "1701",
1670 };
1671 break;
1672 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1673 racoon = new String[] {
1674 iface, profile.server, "udprsa", privateKey, userCert,
1675 caCert, serverCert, "1701",
1676 };
1677 break;
1678 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1679 racoon = new String[] {
1680 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1681 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1682 };
1683 break;
1684 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1685 racoon = new String[] {
1686 iface, profile.server, "xauthrsa", privateKey, userCert,
1687 caCert, serverCert, profile.username, profile.password, "", gateway,
1688 };
1689 break;
1690 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1691 racoon = new String[] {
1692 iface, profile.server, "hybridrsa",
1693 caCert, serverCert, profile.username, profile.password, "", gateway,
1694 };
1695 break;
1696 }
1697
1698 // Prepare arguments for mtpd.
1699 String[] mtpd = null;
1700 switch (profile.type) {
1701 case VpnProfile.TYPE_PPTP:
1702 mtpd = new String[] {
1703 iface, "pptp", profile.server, "1723",
1704 "name", profile.username, "password", profile.password,
1705 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1706 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1707 (profile.mppe ? "+mppe" : "nomppe"),
1708 };
1709 break;
1710 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1711 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1712 mtpd = new String[] {
1713 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1714 "name", profile.username, "password", profile.password,
1715 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1716 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1717 };
1718 break;
1719 }
1720
1721 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001722 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001723 config.user = profile.key;
1724 config.interfaze = iface;
1725 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001726
1727 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001728 if (!profile.dnsServers.isEmpty()) {
1729 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1730 }
1731 if (!profile.searchDomains.isEmpty()) {
1732 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1733 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001734 startLegacyVpn(config, racoon, mtpd);
1735 }
1736
1737 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001738 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001739
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001740 // Prepare for the new request.
1741 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001742 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001743
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001744 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001745 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1746 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001747 }
1748
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001749 /** Stop legacy VPN. Permissions must be checked by callers. */
1750 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001751 if (mLegacyVpnRunner != null) {
1752 mLegacyVpnRunner.exit();
1753 mLegacyVpnRunner = null;
1754
1755 synchronized (LegacyVpnRunner.TAG) {
1756 // wait for old thread to completely finish before spinning up
1757 // new instance, otherwise state updates can be out of order.
1758 }
1759 }
1760 }
1761
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001762 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001763 * Return the information of the current ongoing legacy VPN.
1764 */
1765 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001766 // Check if the caller is authorized.
1767 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001768 return getLegacyVpnInfoPrivileged();
1769 }
1770
1771 /**
1772 * Return the information of the current ongoing legacy VPN.
1773 * Callers are responsible for checking permissions if needed.
1774 */
1775 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001776 if (mLegacyVpnRunner == null) return null;
1777
1778 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001779 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001780 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001781 if (mNetworkInfo.isConnected()) {
1782 info.intent = mStatusIntent;
1783 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001784 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001785 }
1786
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001787 public VpnConfig getLegacyVpnConfig() {
1788 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001789 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001790 } else {
1791 return null;
1792 }
1793 }
1794
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001795 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001796 * Bringing up a VPN connection takes time, and that is all this thread
1797 * does. Here we have plenty of time. The only thing we need to take
1798 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001799 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001800 * machine, but it is much easier to read in the current form.
1801 */
1802 private class LegacyVpnRunner extends Thread {
1803 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001804
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001805 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001806 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001807 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001808 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001809 private final AtomicInteger mOuterConnection =
1810 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001811
Chalard Jeandd59ece2017-12-20 13:23:32 +09001812 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001813
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001814 /**
1815 * Watch for the outer connection (passing in the constructor) going away.
1816 */
1817 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1818 @Override
1819 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001820 if (!mEnableTeardown) return;
1821
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001822 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1823 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1824 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1825 NetworkInfo info = (NetworkInfo)intent.getExtra(
1826 ConnectivityManager.EXTRA_NETWORK_INFO);
1827 if (info != null && !info.isConnectedOrConnecting()) {
1828 try {
1829 mObserver.interfaceStatusChanged(mOuterInterface, false);
1830 } catch (RemoteException e) {}
1831 }
1832 }
1833 }
1834 }
1835 };
1836
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001837 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001838 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001839 mConfig = config;
1840 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001841 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001842 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001843 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001844
1845 // This is the interface which VPN is running on,
1846 // mConfig.interfaze will change to point to OUR
1847 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001848 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001849 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001850 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001851 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001852
Paul Jensene75b9e32015-04-06 11:54:53 -04001853 if (!TextUtils.isEmpty(mOuterInterface)) {
1854 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1855 for (Network network : cm.getAllNetworks()) {
1856 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001857 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001858 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1859 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1860 }
1861 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001862 }
1863
1864 IntentFilter filter = new IntentFilter();
1865 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1866 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001867 }
1868
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001869 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001870 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001871 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1872 exit();
1873 }
1874 }
1875
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001876 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001877 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001878 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001879 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001880 try {
1881 mContext.unregisterReceiver(mBroadcastReceiver);
1882 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001883 }
1884
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001885 @Override
1886 public void run() {
1887 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001888 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001889 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001890 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001891 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001892 bringup();
1893 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001894 interrupted(); // Clear interrupt flag if execute called exit.
1895 } catch (InterruptedException e) {
1896 } finally {
1897 for (LocalSocket socket : mSockets) {
1898 IoUtils.closeQuietly(socket);
1899 }
1900 // This sleep is necessary for racoon to successfully complete sending delete
1901 // message to server.
1902 try {
1903 Thread.sleep(50);
1904 } catch (InterruptedException e) {
1905 }
1906 for (String daemon : mDaemons) {
1907 SystemService.stop(daemon);
1908 }
1909 }
1910 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001911 }
1912 }
1913
Chalard Jeandd59ece2017-12-20 13:23:32 +09001914 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001915 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09001916 if (now - mBringupStartTime <= 60000) {
1917 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001918 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001919 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09001920 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001921 }
1922 }
1923
Chalard Jeandd59ece2017-12-20 13:23:32 +09001924 private void bringup() {
1925 // Catch all exceptions so we can clean up a few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001926 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001927 try {
1928 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09001929 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001930
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001931 // Wait for the daemons to stop.
1932 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001933 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001934 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001935 }
1936 }
1937
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001938 // Clear the previous state.
1939 File state = new File("/data/misc/vpn/state");
1940 state.delete();
1941 if (state.exists()) {
1942 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001943 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001944 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001945 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001946
Chia-chi Yehe9107902011-07-02 01:48:50 -07001947 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001948 boolean restart = false;
1949 for (String[] arguments : mArguments) {
1950 restart = restart || (arguments != null);
1951 }
1952 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001953 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001954 return;
1955 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001956 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001957
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001958 // Start the daemon with arguments.
1959 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001960 String[] arguments = mArguments[i];
1961 if (arguments == null) {
1962 continue;
1963 }
1964
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001965 // Start the daemon.
1966 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001967 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001968
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001969 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001970 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001971 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001972 }
1973
1974 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001975 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001976 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001977 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001978
1979 // Wait for the socket to connect.
1980 while (true) {
1981 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001982 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001983 break;
1984 } catch (Exception e) {
1985 // ignore
1986 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09001987 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001988 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001989 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001990
1991 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001992 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001993 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001994 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001995 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001996 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001997 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001998 out.write(bytes.length >> 8);
1999 out.write(bytes.length);
2000 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002001 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002002 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002003 out.write(0xFF);
2004 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002005 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002006
2007 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002008 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002009 while (true) {
2010 try {
2011 if (in.read() == -1) {
2012 break;
2013 }
2014 } catch (Exception e) {
2015 // ignore
2016 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002017 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002018 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002019 }
2020
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002021 // Wait for the daemons to create the new state.
2022 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002023 // Check if a running daemon is dead.
2024 for (int i = 0; i < mDaemons.length; ++i) {
2025 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002026 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002027 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002028 }
2029 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002030 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002031 }
2032
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002033 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002034 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002035 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002036 throw new IllegalStateException("Cannot parse the state");
2037 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002038
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002039 // Set the interface and the addresses in the config.
2040 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002041
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002042 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002043 // Set the routes if they are not set in the config.
2044 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002045 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002046 }
2047
2048 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002049 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002050 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002051 if (!dnsServers.isEmpty()) {
2052 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2053 }
2054 }
2055
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002056 // Set the search domains if they are not set in the config.
2057 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2058 String searchDomains = parameters[4].trim();
2059 if (!searchDomains.isEmpty()) {
2060 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2061 }
2062 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002063
Lorenzo Colitti50262792014-09-19 01:53:35 +09002064 // Add a throw route for the VPN server endpoint, if one was specified.
2065 String endpoint = parameters[5];
2066 if (!endpoint.isEmpty()) {
2067 try {
2068 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2069 if (addr instanceof Inet4Address) {
2070 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2071 } else if (addr instanceof Inet6Address) {
2072 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2073 } else {
2074 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2075 }
2076 } catch (IllegalArgumentException e) {
2077 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2078 }
2079 }
2080
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002081 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002082 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002083 // Set the start time
2084 mConfig.startTime = SystemClock.elapsedRealtime();
2085
Chalard Jeandd59ece2017-12-20 13:23:32 +09002086 // Check if the thread was interrupted while we were waiting on the lock.
2087 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002088
Chia-chi Yehe9107902011-07-02 01:48:50 -07002089 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002090 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002091 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002092 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002093
2094 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002095 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002096 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002097
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002098 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002099
2100 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002101 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002102 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002103 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002104 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002105 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002106 }
2107 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002108
2109 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002110 * Check all daemons every two seconds. Return when one of them is stopped.
2111 * The caller will move to the disconnected state when this function returns,
2112 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002113 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002114 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002115 if (!mNetworkInfo.isConnected()) {
2116 return;
2117 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002118 while (true) {
2119 Thread.sleep(2000);
2120 for (int i = 0; i < mDaemons.length; i++) {
2121 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2122 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002123 }
2124 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002125 }
2126 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002127 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002128}