blob: df94de2e52d1fc7dd8d6df644334669a40908f0f [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen31a94f42015-02-13 14:18:39 -050020import static android.net.ConnectivityManager.NETID_UNSET;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +090021import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060022import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
23import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti50262792014-09-19 01:53:35 +090024import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090025import static android.net.RouteInfo.RTN_UNREACHABLE;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026
Jeff Davidsonbc19c182014-11-11 13:20:01 -080027import android.Manifest;
Robin Lee4d03abc2016-05-09 12:32:27 +010028import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.UserIdInt;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070031import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070032import android.app.AppOpsManager;
Tony Mak1a405fe2016-06-30 11:19:20 +010033import android.app.Notification;
34import android.app.NotificationManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070035import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070036import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.content.Context;
39import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070040import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041import android.content.ServiceConnection;
Charles Hea0a87e82017-05-15 17:07:18 +010042import android.content.pm.ApplicationInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040044import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070045import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070046import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070048import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090049import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070050import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070051import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070052import android.net.LocalSocket;
53import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080054import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.NetworkAgent;
56import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070059import android.net.NetworkMisc;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090060import android.net.NetworkUtils;
Jeff Sharkey82f85212012-08-24 11:17:25 -070061import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040062import android.net.UidRange;
Robin Lee812800c2016-05-13 15:38:08 +010063import android.net.Uri;
Charles Hea0a87e82017-05-15 17:07:18 +010064import android.net.VpnService;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070065import android.os.Binder;
Charles Hea0a87e82017-05-15 17:07:18 +010066import android.os.Build.VERSION_CODES;
67import android.os.Bundle;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080068import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070069import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070070import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070072import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import android.os.ParcelFileDescriptor;
Robin Lee812800c2016-05-13 15:38:08 +010074import android.os.PatternMatcher;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070075import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070076import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070077import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070078import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070079import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070080import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010081import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070082import android.security.Credentials;
83import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040084import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010085import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.util.Log;
87
Tony Mak1a405fe2016-06-30 11:19:20 +010088import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070089import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010090import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040091import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070092import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070093import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080094import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050096import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060097import com.android.internal.util.ArrayUtils;
98import com.android.server.ConnectivityService;
Christopher Tatee0be7e82017-02-08 17:38:20 -080099import com.android.server.DeviceIdleController;
100import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700102
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700103import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700104import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700105import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700106import java.io.OutputStream;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900107import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700109import java.net.Inet6Address;
110import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700111import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700113import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100114import java.util.Collection;
115import java.util.Collections;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900116import java.util.Comparator;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +0100118import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400119import java.util.SortedSet;
120import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700121import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700122
Bernie Innocenti00000fe2018-05-28 22:04:37 +0900123import libcore.io.IoUtils;
124
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;
Chad Brubakerc2865192013-07-10 14:46:23 -0700175 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400176 private NetworkAgent mNetworkAgent;
177 private final Looper mLooper;
178 private final NetworkCapabilities mNetworkCapabilities;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000179 private final SystemServices mSystemServices;
Chad Brubakerc2865192013-07-10 14:46:23 -0700180
Robin Lee4d03abc2016-05-09 12:32:27 +0100181 /**
Robin Lee17e61832016-05-09 13:46:28 +0100182 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
183 * only applies to {@link VpnService} connections.
184 */
185 private boolean mAlwaysOn = false;
186
187 /**
188 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
189 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
190 * not set.
191 */
192 private boolean mLockdown = false;
193
194 /**
Robin Lee17e61832016-05-09 13:46:28 +0100195 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
196 * when VPN is not running. For example, during system startup or after a crash.
197 * @see mLockdown
198 */
199 @GuardedBy("this")
200 private Set<UidRange> mBlockedUsers = new ArraySet<>();
201
Chalard Jeandd59ece2017-12-20 13:23:32 +0900202 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400203 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700204
Chalard Jeandd59ece2017-12-20 13:23:32 +0900205 // Listen to package removal and change events (update/uninstall) for this user
Robin Lee812800c2016-05-13 15:38:08 +0100206 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
207 @Override
208 public void onReceive(Context context, Intent intent) {
209 final Uri data = intent.getData();
210 final String packageName = data == null ? null : data.getSchemeSpecificPart();
211 if (packageName == null) {
212 return;
213 }
214
215 synchronized (Vpn.this) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900216 // Avoid race where always-on package has been unset
Robin Lee812800c2016-05-13 15:38:08 +0100217 if (!packageName.equals(getAlwaysOnPackage())) {
218 return;
219 }
220
221 final String action = intent.getAction();
Chalard Jeandd59ece2017-12-20 13:23:32 +0900222 Log.i(TAG, "Received broadcast " + action + " for always-on VPN package "
223 + packageName + " in user " + mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100224
225 switch(action) {
226 case Intent.ACTION_PACKAGE_REPLACED:
227 // Start vpn after app upgrade
228 startAlwaysOnVpn();
229 break;
230 case Intent.ACTION_PACKAGE_REMOVED:
231 final boolean isPackageRemoved = !intent.getBooleanExtra(
232 Intent.EXTRA_REPLACING, false);
233 if (isPackageRemoved) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000234 setAlwaysOnPackage(null, false);
Robin Lee812800c2016-05-13 15:38:08 +0100235 }
236 break;
237 }
238 }
239 }
240 };
241
242 private boolean mIsPackageIntentReceiverRegistered = false;
243
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400244 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000245 @UserIdInt int userHandle) {
246 this(looper, context, netService, userHandle, new SystemServices(context));
247 }
248
249 @VisibleForTesting
250 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
251 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700252 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400253 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400254 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400255 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000256 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400257
258 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400259 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700260
261 try {
262 netService.registerObserver(mObserver);
263 } catch (RemoteException e) {
264 Log.wtf(TAG, "Problem registering observer", e);
265 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400266
Chalard Jeandd59ece2017-12-20 13:23:32 +0900267 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
268 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400269 mNetworkCapabilities = new NetworkCapabilities();
270 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
271 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600272 updateCapabilities();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000273
274 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700275 }
276
Jeff Sharkey57666932013-04-30 17:01:57 -0700277 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900278 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700279 * teardown. When {@code false}, teardown is handled externally by someone
280 * else.
281 */
282 public void setEnableTeardown(boolean enableTeardown) {
283 mEnableTeardown = enableTeardown;
284 }
285
Jeff Sharkey899223b2012-08-04 15:24:58 -0700286 /**
287 * Update current state, dispaching event to listeners.
288 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100289 @VisibleForTesting
290 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700291 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
292 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400293 if (mNetworkAgent != null) {
294 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
295 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100296 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700297 }
298
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600299 public void updateCapabilities() {
300 final Network[] underlyingNetworks = (mConfig != null) ? mConfig.underlyingNetworks : null;
301 updateCapabilities(mContext.getSystemService(ConnectivityManager.class), underlyingNetworks,
302 mNetworkCapabilities);
303
304 if (mNetworkAgent != null) {
305 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
306 }
307 }
308
309 @VisibleForTesting
310 public static void updateCapabilities(ConnectivityManager cm, Network[] underlyingNetworks,
311 NetworkCapabilities caps) {
312 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
313 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
314 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
315 boolean metered = false;
316 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900317 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600318
319 if (ArrayUtils.isEmpty(underlyingNetworks)) {
320 // No idea what the underlying networks are; assume sane defaults
321 metered = true;
322 roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900323 congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600324 } else {
325 for (Network underlying : underlyingNetworks) {
326 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700327 if (underlyingCaps == null) continue;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600328 for (int underlyingType : underlyingCaps.getTransportTypes()) {
329 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
330 }
331
332 // When we have multiple networks, we have to assume the
333 // worst-case link speed and restrictions.
334 downKbps = NetworkCapabilities.minBandwidth(downKbps,
335 underlyingCaps.getLinkDownstreamBandwidthKbps());
336 upKbps = NetworkCapabilities.minBandwidth(upKbps,
337 underlyingCaps.getLinkUpstreamBandwidthKbps());
338 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
339 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900340 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600341 }
342 }
343
344 caps.setTransportTypes(transportTypes);
345 caps.setLinkDownstreamBandwidthKbps(downKbps);
346 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900347 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
348 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
349 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600350 }
351
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700352 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000353 * Chooses whether to force all connections to go though VPN.
354 *
355 * Used to enable/disable legacy VPN lockdown.
356 *
357 * This uses the same ip rule mechanism as {@link #setAlwaysOnPackage(String, boolean)};
358 * previous settings from calling that function will be replaced and saved with the
359 * always-on state.
360 *
361 * @param lockdown whether to prevent all traffic outside of a VPN.
362 */
363 public synchronized void setLockdown(boolean lockdown) {
364 enforceControlPermissionOrInternalCaller();
365
366 setVpnForcedLocked(lockdown);
367 mLockdown = lockdown;
368
369 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
370 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
371 if (mAlwaysOn) {
372 saveAlwaysOnPackage();
373 }
374 }
375
376 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100377 * Checks if a VPN app supports always-on mode.
378 *
379 * In order to support the always-on feature, an app has to
380 * <ul>
381 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100382 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
383 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100384 * </ul>
385 *
386 * @param packageName the canonical package name of the VPN app
387 * @return {@code true} if and only if the VPN app exists and supports always-on mode
388 */
389 public boolean isAlwaysOnPackageSupported(String packageName) {
390 enforceSettingsPermission();
391
392 if (packageName == null) {
393 return false;
394 }
395
396 PackageManager pm = mContext.getPackageManager();
397 ApplicationInfo appInfo = null;
398 try {
399 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
400 } catch (NameNotFoundException unused) {
401 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
402 }
403 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
404 return false;
405 }
406
407 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
408 intent.setPackage(packageName);
409 List<ResolveInfo> services =
410 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
411 if (services == null || services.size() == 0) {
412 return false;
413 }
414
415 for (ResolveInfo rInfo : services) {
416 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100417 if (metaData != null &&
418 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100419 return false;
420 }
421 }
422
423 return true;
424 }
425
426 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000427 * Configures an always-on VPN connection through a specific application.
428 * This connection is automatically granted and persisted after a reboot.
429 *
430 * <p>The designated package should exist and declare a {@link VpnService} in its
431 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
432 * otherwise the call will fail.
433 *
Charles Hea0a87e82017-05-15 17:07:18 +0100434 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
435 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
436 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
437 *
Robin Lee17e61832016-05-09 13:46:28 +0100438 * @param packageName the package to designate as always-on VPN supplier.
439 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100440 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000441 */
Robin Lee17e61832016-05-09 13:46:28 +0100442 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000443 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000444
445 if (setAlwaysOnPackageInternal(packageName, lockdown)) {
446 saveAlwaysOnPackage();
447 return true;
448 }
449 return false;
450 }
451
452 /**
453 * Configures an always-on VPN connection through a specific application, the same as
454 * {@link #setAlwaysOnPackage}.
455 *
456 * Does not perform permission checks. Does not persist any of the changes to storage.
457 *
458 * @param packageName the package to designate as always-on VPN supplier.
459 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
460 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
461 */
462 @GuardedBy("this")
463 private boolean setAlwaysOnPackageInternal(String packageName, boolean lockdown) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100464 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
465 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
466 return false;
467 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000468
Robin Lee244ce8e2016-01-05 18:03:46 +0000469 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100470 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000471 if (!setPackageAuthorization(packageName, true)) {
472 return false;
473 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100474 mAlwaysOn = true;
475 } else {
476 packageName = VpnConfig.LEGACY_VPN;
477 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000478 }
479
Robin Lee17e61832016-05-09 13:46:28 +0100480 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100481 if (isCurrentPreparedPackage(packageName)) {
482 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
483 } else {
484 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100485 prepareInternal(packageName);
486 }
Robin Lee812800c2016-05-13 15:38:08 +0100487 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100488 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000489 return true;
490 }
491
Robin Lee9ff1a582016-06-10 16:41:10 +0100492 private static boolean isNullOrLegacyVpn(String packageName) {
493 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
494 }
495
Robin Lee812800c2016-05-13 15:38:08 +0100496 private void unregisterPackageChangeReceiverLocked() {
Robin Lee812800c2016-05-13 15:38:08 +0100497 if (mIsPackageIntentReceiverRegistered) {
498 mContext.unregisterReceiver(mPackageIntentReceiver);
499 mIsPackageIntentReceiverRegistered = false;
500 }
501 }
502
503 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
504 // Unregister IntentFilter listening for previous always-on package change
505 unregisterPackageChangeReceiverLocked();
506
Robin Lee9ff1a582016-06-10 16:41:10 +0100507 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100508 mIsPackageIntentReceiverRegistered = true;
509
510 IntentFilter intentFilter = new IntentFilter();
511 // Protected intent can only be sent by system. No permission required in register.
512 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
513 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
514 intentFilter.addDataScheme("package");
515 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
516 mContext.registerReceiverAsUser(
517 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
518 }
519 }
520
Robin Lee244ce8e2016-01-05 18:03:46 +0000521 /**
522 * @return the package name of the VPN controller responsible for always-on VPN,
523 * or {@code null} if none is set or always-on VPN is controlled through
524 * lockdown instead.
525 * @hide
526 */
527 public synchronized String getAlwaysOnPackage() {
528 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100529 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000530 }
531
532 /**
Robin Lee812800c2016-05-13 15:38:08 +0100533 * Save the always-on package and lockdown config into Settings.Secure
534 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000535 @GuardedBy("this")
536 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100537 final long token = Binder.clearCallingIdentity();
538 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000539 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100540 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000541 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000542 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100543 } finally {
544 Binder.restoreCallingIdentity(token);
545 }
546 }
547
548 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000549 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100550 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000551 @GuardedBy("this")
552 private void loadAlwaysOnPackage() {
553 final long token = Binder.clearCallingIdentity();
554 try {
555 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
556 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
557 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
558 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
559 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown);
560 } finally {
561 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100562 }
563 }
564
565 /**
566 * @return {@code true} if the service was started, the service was already connected, or there
567 * was no always-on VPN to start. {@code false} otherwise.
568 */
569 public boolean startAlwaysOnVpn() {
570 final String alwaysOnPackage;
571 synchronized (this) {
572 alwaysOnPackage = getAlwaysOnPackage();
573 // Skip if there is no service to start.
574 if (alwaysOnPackage == null) {
575 return true;
576 }
Charles Hea0a87e82017-05-15 17:07:18 +0100577 // Remove always-on VPN if it's not supported.
578 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
579 setAlwaysOnPackage(null, false);
580 return false;
581 }
Robin Lee812800c2016-05-13 15:38:08 +0100582 // Skip if the service is already established. This isn't bulletproof: it's not bound
583 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
584 // which may restart the connection.
585 if (getNetworkInfo().isConnected()) {
586 return true;
587 }
588 }
589
Christopher Tatee0be7e82017-02-08 17:38:20 -0800590 // Tell the OS that background services in this app need to be allowed for
591 // a short time, so we can bootstrap the VPN service.
592 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100593 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800594 DeviceIdleController.LocalService idleController =
595 LocalServices.getService(DeviceIdleController.LocalService.class);
596 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900597 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800598
599 // Start the VPN service declared in the app's manifest.
600 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
601 serviceIntent.setPackage(alwaysOnPackage);
602 try {
603 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
604 } catch (RuntimeException e) {
605 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
606 return false;
607 }
608 } finally {
609 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100610 }
611 }
612
613 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700614 * Prepare for a VPN application. This method is designed to solve
615 * race conditions. It first compares the current prepared package
616 * with {@code oldPackage}. If they are the same, the prepared
617 * package is revoked and replaced with {@code newPackage}. If
618 * {@code oldPackage} is {@code null}, the comparison is omitted.
619 * If {@code newPackage} is the same package or {@code null}, the
620 * revocation is omitted. This method returns {@code true} if the
621 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700622 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700623 * Legacy VPN is handled specially since it is not a real package.
624 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
625 * it can be revoked by itself.
626 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900627 * Note: when we added VPN pre-consent in
628 * https://android.googlesource.com/platform/frameworks/base/+/0554260
629 * the names oldPackage and newPackage became misleading, because when
630 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100631 *
632 * Their meanings actually are:
633 *
634 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
635 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100636 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100637 * and revoke any current app VPN and re-prepare legacy vpn.
638 *
Robin Lee812800c2016-05-13 15:38:08 +0100639 * TODO: Rename the variables - or split this method into two - and end this confusion.
640 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
641 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100642 *
643 * @param oldPackage The package name of the old VPN application
644 * @param newPackage The package name of the new VPN application
645 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900646 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700647 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700648 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700649 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100650 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100651 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100652 return false;
653 }
654
Chalard Jeandd59ece2017-12-20 13:23:32 +0900655 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100656 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700657 // The package doesn't match. We return false (to obtain user consent) unless the
658 // user has already consented to that VPN package.
659 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
660 prepareInternal(oldPackage);
661 return true;
662 }
663 return false;
664 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
665 && !isVpnUserPreConsented(oldPackage)) {
666 // Currently prepared VPN is revoked, so unprepare it and return false.
667 prepareInternal(VpnConfig.LEGACY_VPN);
668 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700669 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700670 }
671
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700672 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700673 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100674 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700675 return true;
676 }
677
Robin Lee1b1bcd72016-02-12 18:11:30 +0000678 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700679 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700680
Victor Chang98a633a2016-05-27 17:30:49 +0100681 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100682 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100683 return false;
684 }
685
Jeff Davidson11008a72014-11-20 13:12:46 -0800686 prepareInternal(newPackage);
687 return true;
688 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700689
Victor Chang98a633a2016-05-27 17:30:49 +0100690 private boolean isCurrentPreparedPackage(String packageName) {
691 // We can't just check that packageName matches mPackage, because if the app was uninstalled
692 // and reinstalled it will no longer be prepared. Instead check the UID.
693 return getAppUid(packageName, mUserHandle) == mOwnerUID;
694 }
695
Jeff Davidson11008a72014-11-20 13:12:46 -0800696 /** Prepare the VPN for the given package. Does not perform permission checks. */
697 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400698 long token = Binder.clearCallingIdentity();
699 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800700 // Reset the interface.
701 if (mInterface != null) {
702 mStatusIntent = null;
703 agentDisconnect();
704 jniReset(mInterface);
705 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900706 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800707 }
708
709 // Revoke the connection or stop LegacyVpnRunner.
710 if (mConnection != null) {
711 try {
712 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
713 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
714 } catch (Exception e) {
715 // ignore
716 }
717 mContext.unbindService(mConnection);
718 mConnection = null;
719 } else if (mLegacyVpnRunner != null) {
720 mLegacyVpnRunner.exit();
721 mLegacyVpnRunner = null;
722 }
723
724 try {
725 mNetd.denyProtect(mOwnerUID);
726 } catch (Exception e) {
727 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
728 }
729
730 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
731 mPackage = newPackage;
732 mOwnerUID = getAppUid(newPackage, mUserHandle);
733 try {
734 mNetd.allowProtect(mOwnerUID);
735 } catch (Exception e) {
736 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
737 }
738 mConfig = null;
739
740 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000741 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400742 } finally {
743 Binder.restoreCallingIdentity(token);
744 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700745 }
746
Jeff Davidson05542602014-08-11 14:07:27 -0700747 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100748 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700749 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000750 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700751 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000752 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700753
Robin Lee3b3dd942015-05-12 18:14:58 +0100754 int uid = getAppUid(packageName, mUserHandle);
755 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
756 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000757 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700758 }
759
760 long token = Binder.clearCallingIdentity();
761 try {
762 AppOpsManager appOps =
763 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100764 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700765 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000766 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700767 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100768 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700769 } finally {
770 Binder.restoreCallingIdentity(token);
771 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000772 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700773 }
774
775 private boolean isVpnUserPreConsented(String packageName) {
776 AppOpsManager appOps =
777 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
778
779 // Verify that the caller matches the given package and has permission to activate VPNs.
780 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
781 packageName) == AppOpsManager.MODE_ALLOWED;
782 }
783
Paul Jensen0784eea2014-08-19 16:00:24 -0400784 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700785 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400786 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700787 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400788 PackageManager pm = mContext.getPackageManager();
789 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700790 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700791 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400792 } catch (NameNotFoundException e) {
793 result = -1;
794 }
795 return result;
796 }
797
798 public NetworkInfo getNetworkInfo() {
799 return mNetworkInfo;
800 }
801
Paul Jensen31a94f42015-02-13 14:18:39 -0500802 public int getNetId() {
803 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
804 }
805
Lorenzo Colitti60446162014-09-20 00:14:31 +0900806 private LinkProperties makeLinkProperties() {
807 boolean allowIPv4 = mConfig.allowIPv4;
808 boolean allowIPv6 = mConfig.allowIPv6;
809
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400810 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900811
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400812 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700813
Lorenzo Colitti60446162014-09-20 00:14:31 +0900814 if (mConfig.addresses != null) {
815 for (LinkAddress address : mConfig.addresses) {
816 lp.addLinkAddress(address);
817 allowIPv4 |= address.getAddress() instanceof Inet4Address;
818 allowIPv6 |= address.getAddress() instanceof Inet6Address;
819 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400820 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900821
822 if (mConfig.routes != null) {
823 for (RouteInfo route : mConfig.routes) {
824 lp.addRoute(route);
825 InetAddress address = route.getDestination().getAddress();
826 allowIPv4 |= address instanceof Inet4Address;
827 allowIPv6 |= address instanceof Inet6Address;
828 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400829 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700830
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400831 if (mConfig.dnsServers != null) {
832 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700833 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
834 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900835 allowIPv4 |= address instanceof Inet4Address;
836 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400837 }
838 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700839
Lorenzo Colitti60446162014-09-20 00:14:31 +0900840 if (!allowIPv4) {
841 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
842 }
843 if (!allowIPv6) {
844 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
845 }
846
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400847 // Concatenate search domains into a string.
848 StringBuilder buffer = new StringBuilder();
849 if (mConfig.searchDomains != null) {
850 for (String domain : mConfig.searchDomains) {
851 buffer.append(domain).append(' ');
852 }
853 }
854 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700855
Lorenzo Colitti60446162014-09-20 00:14:31 +0900856 // TODO: Stop setting the MTU in jniCreate and set it here.
857
858 return lp;
859 }
860
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900861 /**
862 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
863 *
864 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
865 * space or to most of the IPv6 address space, where "most" is defined by the value of the
866 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
867 * by any of the routes, then it's decided that most of the space is routed.
868 * @hide
869 */
870 @VisibleForTesting
871 static boolean providesRoutesToMostDestinations(LinkProperties lp) {
Chalard Jeane0d26f62018-03-29 14:10:44 +0900872 final List<RouteInfo> routes = lp.getAllRoutes();
873 if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900874 final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
875 TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
876 TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
Chalard Jeane0d26f62018-03-29 14:10:44 +0900877 for (final RouteInfo route : routes) {
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900878 IpPrefix destination = route.getDestination();
879 if (destination.isIPv4()) {
880 ipv4Prefixes.add(destination);
881 } else {
882 ipv6Prefixes.add(destination);
883 }
884 }
885 if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
886 return true;
887 }
888 return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
889 .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
890 }
891
Lorenzo Colitti60446162014-09-20 00:14:31 +0900892 private void agentConnect() {
893 LinkProperties lp = makeLinkProperties();
894
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900895 if (providesRoutesToMostDestinations(lp)) {
Lorenzo Colitti60446162014-09-20 00:14:31 +0900896 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
897 } else {
898 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
899 }
900
Robin Lee323f29d2016-05-04 16:38:06 +0100901 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700902
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700903 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100904 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700905
Chalard Jeanf474fc32018-01-17 15:10:05 +0900906 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900907 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
908 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400909 long token = Binder.clearCallingIdentity();
910 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900911 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900912 mNetworkInfo, mNetworkCapabilities, lp,
913 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700914 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400915 public void unwanted() {
916 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700917 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400918 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700919 } finally {
920 Binder.restoreCallingIdentity(token);
921 }
Robin Lee323f29d2016-05-04 16:38:06 +0100922 mNetworkInfo.setIsAvailable(true);
923 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400924 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700925
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700926 private boolean canHaveRestrictedProfile(int userId) {
927 long token = Binder.clearCallingIdentity();
928 try {
929 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
930 } finally {
931 Binder.restoreCallingIdentity(token);
932 }
933 }
934
Tony Mak1a405fe2016-06-30 11:19:20 +0100935 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400936 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100937 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
938 networkInfo.setIsAvailable(false);
939 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400940 networkAgent.sendNetworkInfo(networkInfo);
941 }
942 }
943
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400944 private void agentDisconnect() {
945 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100946 mNetworkInfo.setIsAvailable(false);
947 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400948 mNetworkAgent = null;
949 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700950 }
951
952 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700953 * Establish a VPN network and return the file descriptor of the VPN
954 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700955 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700956 *
957 * @param config The parameters to configure the network.
958 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700959 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700960 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700961 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700962 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400963 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700964 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700965 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700966 // Check to ensure consent hasn't been revoked since we were prepared.
967 if (!isVpnUserPreConsented(mPackage)) {
968 return null;
969 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700970 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700971 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
972 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700973 long token = Binder.clearCallingIdentity();
974 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700975 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400976 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100977 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700978 throw new SecurityException("Restricted users cannot establish VPNs");
979 }
980
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700981 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900982 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700983 if (info == null) {
984 throw new SecurityException("Cannot find " + config.user);
985 }
986 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
987 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
988 }
989 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900990 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700991 } finally {
992 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700993 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700994
Chad Brubaker850eb672014-03-21 21:02:47 +0000995 // Save the old config in case we need to go back.
996 VpnConfig oldConfig = mConfig;
997 String oldInterface = mInterface;
998 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400999 NetworkAgent oldNetworkAgent = mNetworkAgent;
1000 mNetworkAgent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001001 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +00001002
Chia-chi Yehe9107902011-07-02 01:48:50 -07001003 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001004 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001005 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001006 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001007 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001008
Chad Brubakerc2865192013-07-10 14:46:23 -07001009 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001010 StringBuilder builder = new StringBuilder();
1011 for (LinkAddress address : config.addresses) {
1012 builder.append(" " + address);
1013 }
1014 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001015 throw new IllegalArgumentException("At least one address must be specified");
1016 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001017 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001018 if (!mContext.bindServiceAsUser(intent, connection,
1019 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1020 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001021 throw new IllegalStateException("Cannot bind " + config.user);
1022 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001023
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001024 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001025 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001026
1027 // Fill more values.
1028 config.user = mPackage;
1029 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001030 config.startTime = SystemClock.elapsedRealtime();
1031 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001032
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001033 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001034 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001035
1036 if (oldConnection != null) {
1037 mContext.unbindService(oldConnection);
1038 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001039 // Remove the old tun's user forwarding rules
1040 // The new tun's user rules have already been added so they will take over
1041 // as rules are deleted. This prevents data leakage as the rules are moved over.
1042 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +00001043 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001044 jniReset(oldInterface);
1045 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001046
1047 try {
1048 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1049 } catch (IOException e) {
1050 throw new IllegalStateException(
1051 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1052 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001053 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001054 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001055 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001056 // restore old state
1057 mConfig = oldConfig;
1058 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001059 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001060 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001061 mInterface = oldInterface;
1062 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001063 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001064 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001065 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001066 }
1067
Chad Brubakerc2865192013-07-10 14:46:23 -07001068 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001069 return mNetworkAgent != null && mInterface != null;
1070 }
1071
1072 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1073 // that a call to mutate VPN state is admissible.
1074 private boolean isCallerEstablishedOwnerLocked() {
1075 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001076 }
1077
Paul Jensen0784eea2014-08-19 16:00:24 -04001078 // Note: Return type guarantees results are deduped and sorted, which callers require.
1079 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
1080 SortedSet<Integer> uids = new TreeSet<Integer>();
1081 for (String app : packageNames) {
1082 int uid = getAppUid(app, userHandle);
1083 if (uid != -1) uids.add(uid);
1084 }
1085 return uids;
1086 }
1087
Robin Lee4d03abc2016-05-09 12:32:27 +01001088 /**
1089 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1090 * associated with one user, and any restricted profiles attached to that user.
1091 *
1092 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1093 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1094 * in each user and profile will be included.
1095 *
1096 * @param userHandle The userId to create UID ranges for along with any of its restricted
1097 * profiles.
1098 * @param allowedApplications (optional) whitelist of applications to include.
1099 * @param disallowedApplications (optional) blacklist of applications to exclude.
1100 */
1101 @VisibleForTesting
1102 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1103 @Nullable List<String> allowedApplications,
1104 @Nullable List<String> disallowedApplications) {
1105 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001106
Robin Lee4d03abc2016-05-09 12:32:27 +01001107 // Assign the top-level user to the set of ranges
1108 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1109
1110 // If the user can have restricted profiles, assign all its restricted profiles too
1111 if (canHaveRestrictedProfile(userHandle)) {
1112 final long token = Binder.clearCallingIdentity();
1113 List<UserInfo> users;
1114 try {
Robin Lee17e61832016-05-09 13:46:28 +01001115 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001116 } finally {
1117 Binder.restoreCallingIdentity(token);
1118 }
1119 for (UserInfo user : users) {
1120 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1121 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1122 }
1123 }
1124 }
1125 return ranges;
1126 }
1127
1128 /**
1129 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1130 * associated with one user.
1131 *
1132 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1133 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1134 * in the user will be included.
1135 *
1136 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1137 * @param userHandle The userId to add to {@param ranges}.
1138 * @param allowedApplications (optional) whitelist of applications to include.
1139 * @param disallowedApplications (optional) blacklist of applications to exclude.
1140 */
1141 @VisibleForTesting
1142 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1143 @Nullable List<String> allowedApplications,
1144 @Nullable List<String> disallowedApplications) {
1145 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001146 // Add ranges covering all UIDs for allowedApplications.
1147 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001148 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001149 if (start == -1) {
1150 start = uid;
1151 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001152 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001153 start = uid;
1154 }
1155 stop = uid;
1156 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001157 if (start != -1) ranges.add(new UidRange(start, stop));
1158 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001159 // Add all ranges for user skipping UIDs for disallowedApplications.
1160 final UidRange userRange = UidRange.createForUser(userHandle);
1161 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001162 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001163 if (uid == start) {
1164 start++;
1165 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001166 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001167 start = uid + 1;
1168 }
1169 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001170 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001171 } else {
1172 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001173 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001174 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001175 }
1176
Paul Jensen0784eea2014-08-19 16:00:24 -04001177 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1178 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001179 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1180 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1181 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001182 final UidRange userRange = UidRange.createForUser(userHandle);
1183 final List<UidRange> ranges = new ArrayList<UidRange>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001184 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001185 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001186 ranges.add(range);
1187 }
1188 }
1189 return ranges;
1190 }
1191
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001192 public void onUserAdded(int userHandle) {
1193 // If the user is restricted tie them to the parent user's VPN
1194 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001195 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001196 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001197 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1198 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001199 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001200 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001201 mConfig.disallowedApplications);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001202 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001203 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001204 } catch (Exception e) {
1205 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001206 }
Robin Lee17e61832016-05-09 13:46:28 +01001207 }
Robin Leec3736bc2017-03-10 16:19:54 +00001208 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001209 }
1210 }
1211 }
1212
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001213 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001214 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001215 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001216 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001217 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001218 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1219 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001220 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001221 final List<UidRange> removedRanges =
1222 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001223 existingRanges.removeAll(removedRanges);
1224 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001225 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001226 } catch (Exception e) {
1227 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1228 }
1229 }
Robin Leec3736bc2017-03-10 16:19:54 +00001230 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001231 }
1232 }
1233 }
1234
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001235 /**
Robin Lee17e61832016-05-09 13:46:28 +01001236 * Called when the user associated with this VPN has just been stopped.
1237 */
1238 public synchronized void onUserStopped() {
1239 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001240 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001241 mAlwaysOn = false;
1242
Robin Lee812800c2016-05-13 15:38:08 +01001243 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001244 // Quit any active connections
1245 agentDisconnect();
1246 }
1247
1248 /**
1249 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1250 * service app itself, to only sockets that have had {@code protect()} called on them. All
1251 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1252 *
1253 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1254 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1255 *
1256 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1257 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1258 *
1259 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1260 * {@link Vpn} goes through a VPN connection or is blocked until one is
1261 * available, {@code false} to lift the requirement.
1262 *
1263 * @see #mBlockedUsers
1264 */
1265 @GuardedBy("this")
1266 private void setVpnForcedLocked(boolean enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001267 final List<String> exemptedPackages =
1268 isNullOrLegacyVpn(mPackage) ? null : Collections.singletonList(mPackage);
Robin Lee17e61832016-05-09 13:46:28 +01001269 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
Robin Leec3736bc2017-03-10 16:19:54 +00001270
1271 Set<UidRange> addedRanges = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001272 if (enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001273 addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
Robin Lee17e61832016-05-09 13:46:28 +01001274 /* allowedApplications */ null,
Robin Leec3736bc2017-03-10 16:19:54 +00001275 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001276
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001277 // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
1278 // directly from the kernel and is marked as uid=0. So we adjust the range to allow
1279 // it through (b/69873852).
1280 for (UidRange range : addedRanges) {
1281 if (range.start == 0) {
1282 addedRanges.remove(range);
1283 if (range.stop != 0) {
1284 addedRanges.add(new UidRange(1, range.stop));
1285 }
1286 }
1287 }
1288
Robin Lee17e61832016-05-09 13:46:28 +01001289 removedRanges.removeAll(addedRanges);
1290 addedRanges.removeAll(mBlockedUsers);
Robin Lee17e61832016-05-09 13:46:28 +01001291 }
Robin Leec3736bc2017-03-10 16:19:54 +00001292
1293 setAllowOnlyVpnForUids(false, removedRanges);
1294 setAllowOnlyVpnForUids(true, addedRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001295 }
1296
1297 /**
1298 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1299 * to make connections through sockets that have had {@code protect()} called on them.
1300 *
1301 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1302 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1303 * {@code true}) or to remove.
1304 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1305 * including added ranges that already existed or removed ones that didn't.
1306 */
1307 @GuardedBy("this")
1308 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1309 if (ranges.size() == 0) {
1310 return true;
1311 }
1312 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1313 try {
1314 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1315 } catch (RemoteException | RuntimeException e) {
1316 Log.e(TAG, "Updating blocked=" + enforce
1317 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1318 return false;
1319 }
1320 if (enforce) {
1321 mBlockedUsers.addAll(ranges);
1322 } else {
1323 mBlockedUsers.removeAll(ranges);
1324 }
1325 return true;
1326 }
1327
1328 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001329 * Return the configuration of the currently running VPN.
1330 */
1331 public VpnConfig getVpnConfig() {
1332 enforceControlPermission();
1333 return mConfig;
1334 }
1335
Jeff Sharkey899223b2012-08-04 15:24:58 -07001336 @Deprecated
1337 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1338 try {
1339 mObserver.interfaceStatusChanged(iface, up);
1340 } catch (RemoteException e) {
1341 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001342 }
1343 }
1344
Jeff Sharkey899223b2012-08-04 15:24:58 -07001345 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1346 @Override
1347 public void interfaceStatusChanged(String interfaze, boolean up) {
1348 synchronized (Vpn.this) {
1349 if (!up && mLegacyVpnRunner != null) {
1350 mLegacyVpnRunner.check(interfaze);
1351 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001352 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001353 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001354
Jeff Sharkey899223b2012-08-04 15:24:58 -07001355 @Override
1356 public void interfaceRemoved(String interfaze) {
1357 synchronized (Vpn.this) {
1358 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001359 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001360 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001361 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001362 mInterface = null;
1363 if (mConnection != null) {
1364 mContext.unbindService(mConnection);
1365 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001366 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001367 } else if (mLegacyVpnRunner != null) {
1368 mLegacyVpnRunner.exit();
1369 mLegacyVpnRunner = null;
1370 }
1371 }
1372 }
1373 }
1374 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001375
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001376 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001377 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001378 }
1379
Robin Lee244ce8e2016-01-05 18:03:46 +00001380 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001381 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001382 // in the system server.
1383 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1384 "Unauthorized Caller");
1385 }
1386
Charles Hea0a87e82017-05-15 17:07:18 +01001387 private void enforceSettingsPermission() {
1388 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1389 "Unauthorized Caller");
1390 }
1391
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001392 private class Connection implements ServiceConnection {
1393 private IBinder mService;
1394
1395 @Override
1396 public void onServiceConnected(ComponentName name, IBinder service) {
1397 mService = service;
1398 }
1399
1400 @Override
1401 public void onServiceDisconnected(ComponentName name) {
1402 mService = null;
1403 }
1404 }
1405
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001406 private void prepareStatusIntent() {
1407 final long token = Binder.clearCallingIdentity();
1408 try {
1409 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1410 } finally {
1411 Binder.restoreCallingIdentity(token);
1412 }
1413 }
1414
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001415 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001416 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001417 return false;
1418 }
1419 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001420 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001421 return success;
1422 }
1423
1424 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001425 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001426 return false;
1427 }
1428 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001429 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001430 return success;
1431 }
1432
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001433 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1434 if (!isCallerEstablishedOwnerLocked()) {
1435 return false;
1436 }
1437 if (networks == null) {
1438 mConfig.underlyingNetworks = null;
1439 } else {
1440 mConfig.underlyingNetworks = new Network[networks.length];
1441 for (int i = 0; i < networks.length; ++i) {
1442 if (networks[i] == null) {
1443 mConfig.underlyingNetworks[i] = null;
1444 } else {
1445 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1446 }
1447 }
1448 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001449 updateCapabilities();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001450 return true;
1451 }
1452
1453 public synchronized Network[] getUnderlyingNetworks() {
1454 if (!isRunningLocked()) {
1455 return null;
1456 }
1457 return mConfig.underlyingNetworks;
1458 }
1459
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001460 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001461 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001462 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1463 */
1464 public synchronized VpnInfo getVpnInfo() {
1465 if (!isRunningLocked()) {
1466 return null;
1467 }
1468
1469 VpnInfo info = new VpnInfo();
1470 info.ownerUid = mOwnerUID;
1471 info.vpnIface = mInterface;
1472 return info;
1473 }
1474
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001475 public synchronized boolean appliesToUid(int uid) {
1476 if (!isRunningLocked()) {
1477 return false;
1478 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001479 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001480 }
1481
Robin Lee17e61832016-05-09 13:46:28 +01001482 /**
Robin Leeebbcb542016-05-24 16:35:10 +01001483 * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1484 * A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1485 * not connected, or if the VPN is connected but does not apply to the UID.
Robin Lee17e61832016-05-09 13:46:28 +01001486 *
1487 * @see #mBlockedUsers
1488 */
1489 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001490 if (!mLockdown) {
1491 return false;
Robin Lee17e61832016-05-09 13:46:28 +01001492 }
Robin Leeebbcb542016-05-24 16:35:10 +01001493
1494 if (mNetworkInfo.isConnected()) {
1495 return !appliesToUid(uid);
1496 } else {
1497 for (UidRange uidRange : mBlockedUsers) {
1498 if (uidRange.contains(uid)) {
1499 return true;
1500 }
1501 }
1502 return false;
1503 }
Robin Lee17e61832016-05-09 13:46:28 +01001504 }
1505
Tony Mak1a405fe2016-06-30 11:19:20 +01001506 private void updateAlwaysOnNotification(DetailedState networkState) {
1507 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001508
Tony Mak1a405fe2016-06-30 11:19:20 +01001509 final UserHandle user = UserHandle.of(mUserHandle);
1510 final long token = Binder.clearCallingIdentity();
1511 try {
1512 final NotificationManager notificationManager = NotificationManager.from(mContext);
1513 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001514 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001515 return;
1516 }
Charles Heab6f2f62017-07-12 15:30:00 +01001517 final Intent intent = new Intent();
1518 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1519 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1520 intent.putExtra("lockdown", mLockdown);
1521 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001522 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1523 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001524 final Notification.Builder builder =
1525 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1526 .setSmallIcon(R.drawable.vpn_connected)
1527 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1528 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1529 .setContentIntent(configIntent)
1530 .setCategory(Notification.CATEGORY_SYSTEM)
1531 .setVisibility(Notification.VISIBILITY_PUBLIC)
1532 .setOngoing(true)
1533 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001534 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1535 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001536 } finally {
1537 Binder.restoreCallingIdentity(token);
1538 }
1539 }
1540
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001541 /**
1542 * Facade for system service calls that change, or depend on, state outside of
1543 * {@link ConnectivityService} and have hard-to-mock interfaces.
1544 *
1545 * @see com.android.server.connectivity.VpnTest
1546 */
1547 @VisibleForTesting
1548 public static class SystemServices {
1549 private final Context mContext;
1550
1551 public SystemServices(@NonNull Context context) {
1552 mContext = context;
1553 }
1554
1555 /**
1556 * @see PendingIntent#getActivityAsUser()
1557 */
1558 public PendingIntent pendingIntentGetActivityAsUser(
1559 Intent intent, int flags, UserHandle user) {
1560 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1561 null /*options*/, user);
1562 }
1563
1564 /**
1565 * @see Settings.Secure#putStringForUser
1566 */
1567 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1568 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1569 }
1570
1571 /**
1572 * @see Settings.Secure#putIntForUser
1573 */
1574 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1575 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1576 }
1577
1578 /**
1579 * @see Settings.Secure#getStringForUser
1580 */
1581 public String settingsSecureGetStringForUser(String key, int userId) {
1582 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1583 }
1584
1585 /**
1586 * @see Settings.Secure#getIntForUser
1587 */
1588 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1589 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1590 }
1591 }
1592
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001593 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001594 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001595 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001596 private native void jniReset(String interfaze);
1597 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001598 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1599 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001600
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001601 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1602 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001603 // Currently legacy VPN only works on IPv4.
1604 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001605 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001606 }
1607 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001608
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001609 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001610 }
1611
1612 /**
1613 * Start legacy VPN, controlling native daemons as needed. Creates a
1614 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001615 *
1616 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1617 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1618 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001619 */
1620 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001621 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001622 long token = Binder.clearCallingIdentity();
1623 try {
1624 startLegacyVpnPrivileged(profile, keyStore, egress);
1625 } finally {
1626 Binder.restoreCallingIdentity(token);
1627 }
1628 }
1629
1630 /**
1631 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1632 * permissions under the assumption that the caller is the system.
1633 *
1634 * Callers are responsible for checking permissions if needed.
1635 */
1636 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1637 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001638 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001639 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001640 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1641 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001642 throw new SecurityException("Restricted users cannot establish VPNs");
1643 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001644
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001645 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1646 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1647 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001648
1649 // Load certificates.
1650 String privateKey = "";
1651 String userCert = "";
1652 String caCert = "";
1653 String serverCert = "";
1654 if (!profile.ipsecUserCert.isEmpty()) {
1655 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1656 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001657 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001658 }
1659 if (!profile.ipsecCaCert.isEmpty()) {
1660 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001661 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001662 }
1663 if (!profile.ipsecServerCert.isEmpty()) {
1664 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001665 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001666 }
1667 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1668 throw new IllegalStateException("Cannot load credentials");
1669 }
1670
1671 // Prepare arguments for racoon.
1672 String[] racoon = null;
1673 switch (profile.type) {
1674 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1675 racoon = new String[] {
1676 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1677 profile.ipsecSecret, "1701",
1678 };
1679 break;
1680 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1681 racoon = new String[] {
1682 iface, profile.server, "udprsa", privateKey, userCert,
1683 caCert, serverCert, "1701",
1684 };
1685 break;
1686 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1687 racoon = new String[] {
1688 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1689 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1690 };
1691 break;
1692 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1693 racoon = new String[] {
1694 iface, profile.server, "xauthrsa", privateKey, userCert,
1695 caCert, serverCert, profile.username, profile.password, "", gateway,
1696 };
1697 break;
1698 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1699 racoon = new String[] {
1700 iface, profile.server, "hybridrsa",
1701 caCert, serverCert, profile.username, profile.password, "", gateway,
1702 };
1703 break;
1704 }
1705
1706 // Prepare arguments for mtpd.
1707 String[] mtpd = null;
1708 switch (profile.type) {
1709 case VpnProfile.TYPE_PPTP:
1710 mtpd = new String[] {
1711 iface, "pptp", profile.server, "1723",
1712 "name", profile.username, "password", profile.password,
1713 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1714 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1715 (profile.mppe ? "+mppe" : "nomppe"),
1716 };
1717 break;
1718 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1719 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1720 mtpd = new String[] {
1721 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1722 "name", profile.username, "password", profile.password,
1723 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1724 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1725 };
1726 break;
1727 }
1728
1729 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001730 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001731 config.user = profile.key;
1732 config.interfaze = iface;
1733 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001734
1735 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001736 if (!profile.dnsServers.isEmpty()) {
1737 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1738 }
1739 if (!profile.searchDomains.isEmpty()) {
1740 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1741 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001742 startLegacyVpn(config, racoon, mtpd);
1743 }
1744
1745 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001746 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001747
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001748 // Prepare for the new request.
1749 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001750 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001751
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001752 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001753 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1754 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001755 }
1756
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001757 /** Stop legacy VPN. Permissions must be checked by callers. */
1758 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001759 if (mLegacyVpnRunner != null) {
1760 mLegacyVpnRunner.exit();
1761 mLegacyVpnRunner = null;
1762
1763 synchronized (LegacyVpnRunner.TAG) {
1764 // wait for old thread to completely finish before spinning up
1765 // new instance, otherwise state updates can be out of order.
1766 }
1767 }
1768 }
1769
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001770 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001771 * Return the information of the current ongoing legacy VPN.
1772 */
1773 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001774 // Check if the caller is authorized.
1775 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001776 return getLegacyVpnInfoPrivileged();
1777 }
1778
1779 /**
1780 * Return the information of the current ongoing legacy VPN.
1781 * Callers are responsible for checking permissions if needed.
1782 */
1783 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001784 if (mLegacyVpnRunner == null) return null;
1785
1786 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001787 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001788 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001789 if (mNetworkInfo.isConnected()) {
1790 info.intent = mStatusIntent;
1791 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001792 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001793 }
1794
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001795 public VpnConfig getLegacyVpnConfig() {
1796 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001797 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001798 } else {
1799 return null;
1800 }
1801 }
1802
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001803 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001804 * Bringing up a VPN connection takes time, and that is all this thread
1805 * does. Here we have plenty of time. The only thing we need to take
1806 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001807 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001808 * machine, but it is much easier to read in the current form.
1809 */
1810 private class LegacyVpnRunner extends Thread {
1811 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001812
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001813 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001814 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001815 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001816 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001817 private final AtomicInteger mOuterConnection =
1818 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001819
Chalard Jeandd59ece2017-12-20 13:23:32 +09001820 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001821
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001822 /**
1823 * Watch for the outer connection (passing in the constructor) going away.
1824 */
1825 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1826 @Override
1827 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001828 if (!mEnableTeardown) return;
1829
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001830 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1831 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1832 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1833 NetworkInfo info = (NetworkInfo)intent.getExtra(
1834 ConnectivityManager.EXTRA_NETWORK_INFO);
1835 if (info != null && !info.isConnectedOrConnecting()) {
1836 try {
1837 mObserver.interfaceStatusChanged(mOuterInterface, false);
1838 } catch (RemoteException e) {}
1839 }
1840 }
1841 }
1842 }
1843 };
1844
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001845 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001846 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001847 mConfig = config;
1848 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001849 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001850 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001851 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001852
1853 // This is the interface which VPN is running on,
1854 // mConfig.interfaze will change to point to OUR
1855 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001856 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001857 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001858 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001859 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001860
Paul Jensene75b9e32015-04-06 11:54:53 -04001861 if (!TextUtils.isEmpty(mOuterInterface)) {
1862 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1863 for (Network network : cm.getAllNetworks()) {
1864 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001865 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001866 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1867 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1868 }
1869 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001870 }
1871
1872 IntentFilter filter = new IntentFilter();
1873 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1874 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001875 }
1876
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001877 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001878 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001879 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1880 exit();
1881 }
1882 }
1883
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001884 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001885 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001886 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001887 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001888 try {
1889 mContext.unregisterReceiver(mBroadcastReceiver);
1890 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001891 }
1892
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001893 @Override
1894 public void run() {
1895 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001896 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001897 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001898 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001899 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001900 bringup();
1901 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001902 interrupted(); // Clear interrupt flag if execute called exit.
1903 } catch (InterruptedException e) {
1904 } finally {
1905 for (LocalSocket socket : mSockets) {
1906 IoUtils.closeQuietly(socket);
1907 }
1908 // This sleep is necessary for racoon to successfully complete sending delete
1909 // message to server.
1910 try {
1911 Thread.sleep(50);
1912 } catch (InterruptedException e) {
1913 }
1914 for (String daemon : mDaemons) {
1915 SystemService.stop(daemon);
1916 }
1917 }
1918 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001919 }
1920 }
1921
Chalard Jeandd59ece2017-12-20 13:23:32 +09001922 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001923 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09001924 if (now - mBringupStartTime <= 60000) {
1925 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001926 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001927 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09001928 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001929 }
1930 }
1931
Chalard Jeandd59ece2017-12-20 13:23:32 +09001932 private void bringup() {
1933 // Catch all exceptions so we can clean up a few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001934 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001935 try {
1936 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09001937 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001938
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001939 // Wait for the daemons to stop.
1940 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001941 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001942 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001943 }
1944 }
1945
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001946 // Clear the previous state.
1947 File state = new File("/data/misc/vpn/state");
1948 state.delete();
1949 if (state.exists()) {
1950 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001951 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001952 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001953 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001954
Chia-chi Yehe9107902011-07-02 01:48:50 -07001955 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001956 boolean restart = false;
1957 for (String[] arguments : mArguments) {
1958 restart = restart || (arguments != null);
1959 }
1960 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001961 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001962 return;
1963 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001964 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001965
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001966 // Start the daemon with arguments.
1967 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001968 String[] arguments = mArguments[i];
1969 if (arguments == null) {
1970 continue;
1971 }
1972
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001973 // Start the daemon.
1974 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001975 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001976
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001977 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001978 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001979 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001980 }
1981
1982 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001983 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001984 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001985 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001986
1987 // Wait for the socket to connect.
1988 while (true) {
1989 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001990 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001991 break;
1992 } catch (Exception e) {
1993 // ignore
1994 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09001995 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001996 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001997 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001998
1999 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002000 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002001 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07002002 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002003 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002004 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002005 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002006 out.write(bytes.length >> 8);
2007 out.write(bytes.length);
2008 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002009 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002010 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002011 out.write(0xFF);
2012 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002013 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002014
2015 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002016 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002017 while (true) {
2018 try {
2019 if (in.read() == -1) {
2020 break;
2021 }
2022 } catch (Exception e) {
2023 // ignore
2024 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002025 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002026 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002027 }
2028
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002029 // Wait for the daemons to create the new state.
2030 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002031 // Check if a running daemon is dead.
2032 for (int i = 0; i < mDaemons.length; ++i) {
2033 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002034 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002035 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002036 }
2037 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002038 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002039 }
2040
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002041 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002042 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002043 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002044 throw new IllegalStateException("Cannot parse the state");
2045 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002046
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002047 // Set the interface and the addresses in the config.
2048 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002049
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002050 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002051 // Set the routes if they are not set in the config.
2052 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002053 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002054 }
2055
2056 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002057 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002058 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002059 if (!dnsServers.isEmpty()) {
2060 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2061 }
2062 }
2063
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002064 // Set the search domains if they are not set in the config.
2065 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2066 String searchDomains = parameters[4].trim();
2067 if (!searchDomains.isEmpty()) {
2068 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2069 }
2070 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002071
Lorenzo Colitti50262792014-09-19 01:53:35 +09002072 // Add a throw route for the VPN server endpoint, if one was specified.
2073 String endpoint = parameters[5];
2074 if (!endpoint.isEmpty()) {
2075 try {
2076 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2077 if (addr instanceof Inet4Address) {
2078 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2079 } else if (addr instanceof Inet6Address) {
2080 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2081 } else {
2082 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2083 }
2084 } catch (IllegalArgumentException e) {
2085 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2086 }
2087 }
2088
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002089 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002090 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002091 // Set the start time
2092 mConfig.startTime = SystemClock.elapsedRealtime();
2093
Chalard Jeandd59ece2017-12-20 13:23:32 +09002094 // Check if the thread was interrupted while we were waiting on the lock.
2095 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002096
Chia-chi Yehe9107902011-07-02 01:48:50 -07002097 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002098 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002099 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002100 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002101
2102 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002103 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002104 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002105
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002106 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002107
2108 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002109 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002110 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002111 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002112 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002113 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002114 }
2115 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002116
2117 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002118 * Check all daemons every two seconds. Return when one of them is stopped.
2119 * The caller will move to the disconnected state when this function returns,
2120 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002121 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002122 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002123 if (!mNetworkInfo.isConnected()) {
2124 return;
2125 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002126 while (true) {
2127 Thread.sleep(2000);
2128 for (int i = 0; i < mDaemons.length; i++) {
2129 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2130 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002131 }
2132 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002133 }
2134 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002135 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002136}