blob: 62a1b036daa026bc2cd89eb407730afda7729685 [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;
Charles Hea0a87e82017-05-15 17:07:18 +010063import android.net.VpnService;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.os.Binder;
Charles Hea0a87e82017-05-15 17:07:18 +010065import android.os.Build.VERSION_CODES;
66import android.os.Bundle;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080067import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070068import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070069import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070071import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070073import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070074import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070075import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070076import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070077import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070078import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010079import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import android.security.Credentials;
81import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040082import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010083import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.util.Log;
85
Tony Mak1a405fe2016-06-30 11:19:20 +010086import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070087import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010088import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -040089import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070090import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070091import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080092import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070093import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050094import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060095import com.android.internal.util.ArrayUtils;
96import com.android.server.ConnectivityService;
Christopher Tatee0be7e82017-02-08 17:38:20 -080097import com.android.server.DeviceIdleController;
98import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -070099import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700100
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000101import libcore.io.IoUtils;
102
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700103import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700104import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700105import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700106import java.io.OutputStream;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900107import java.math.BigInteger;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700109import java.net.Inet6Address;
110import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700111import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400112import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700113import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100114import java.util.Collection;
115import java.util.Collections;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900116import java.util.Comparator;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117import java.util.List;
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900118import java.util.Objects;
Robin Lee4d03abc2016-05-09 12:32:27 +0100119import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400120import java.util.SortedSet;
121import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700122import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700123
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124/**
125 * @hide
126 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400127public class Vpn {
128 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700129 private static final String TAG = "Vpn";
130 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131
Christopher Tatee0be7e82017-02-08 17:38:20 -0800132 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
133 // the device idle whitelist during service launch and VPN bootstrap.
Chalard Jeandd59ece2017-12-20 13:23:32 +0900134 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS = 60 * 1000;
Christopher Tatee0be7e82017-02-08 17:38:20 -0800135
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900136 // Settings for how much of the address space should be routed so that Vpn considers
137 // "most" of the address space is routed. This is used to determine whether this Vpn
138 // should be marked with the INTERNET capability.
139 private static final long MOST_IPV4_ADDRESSES_COUNT;
140 private static final BigInteger MOST_IPV6_ADDRESSES_COUNT;
141 static {
142 // 85% of the address space must be routed for Vpn to consider this VPN to provide
143 // INTERNET access.
144 final int howManyPercentIsMost = 85;
145
146 final long twoPower32 = 1L << 32;
147 MOST_IPV4_ADDRESSES_COUNT = twoPower32 * howManyPercentIsMost / 100;
148 final BigInteger twoPower128 = BigInteger.ONE.shiftLeft(128);
149 MOST_IPV6_ADDRESSES_COUNT = twoPower128
150 .multiply(BigInteger.valueOf(howManyPercentIsMost))
151 .divide(BigInteger.valueOf(100));
152 }
Chalard Jeane0d26f62018-03-29 14:10:44 +0900153 // How many routes to evaluate before bailing and declaring this Vpn should provide
Dan Albertee8e6a02019-01-24 21:05:39 +0000154 // the INTERNET capability. This is necessary because computing the adress space is
Chalard Jeane0d26f62018-03-29 14:10:44 +0900155 // O(n²) and this is running in the system service, so a limit is needed to alleviate
156 // the risk of attack.
157 // This is taken as a total of IPv4 + IPV6 routes for simplicity, but the algorithm
158 // is actually O(n²)+O(n²).
159 private static final int MAX_ROUTES_TO_EVALUATE = 150;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900160
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 // TODO: create separate trackers for each unique VPN to support
162 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700163
Chalard Jean546ec6b2018-10-01 12:58:19 +0900164 private final Context mContext;
165 private final NetworkInfo mNetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400166 private String mPackage;
167 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700168 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700169 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700170 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700171 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700172 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173 private final INetworkManagementService mNetd;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900174 @VisibleForTesting
175 protected VpnConfig mConfig;
176 @VisibleForTesting
177 protected NetworkAgent mNetworkAgent;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400178 private final Looper mLooper;
Chalard Jeanf666d0a2018-05-18 21:47:45 +0900179 @VisibleForTesting
180 protected final NetworkCapabilities mNetworkCapabilities;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000181 private final SystemServices mSystemServices;
Chad Brubakerc2865192013-07-10 14:46:23 -0700182
Robin Lee4d03abc2016-05-09 12:32:27 +0100183 /**
Robin Lee17e61832016-05-09 13:46:28 +0100184 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
185 * only applies to {@link VpnService} connections.
186 */
187 private boolean mAlwaysOn = false;
188
189 /**
190 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
191 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
192 * not set.
193 */
194 private boolean mLockdown = false;
195
196 /**
Robin Lee17e61832016-05-09 13:46:28 +0100197 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
198 * when VPN is not running. For example, during system startup or after a crash.
199 * @see mLockdown
200 */
201 @GuardedBy("this")
202 private Set<UidRange> mBlockedUsers = new ArraySet<>();
203
Chalard Jeandd59ece2017-12-20 13:23:32 +0900204 // Handle of the user initiating VPN.
Paul Jensen0784eea2014-08-19 16:00:24 -0400205 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700206
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400207 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000208 @UserIdInt int userHandle) {
209 this(looper, context, netService, userHandle, new SystemServices(context));
210 }
211
212 @VisibleForTesting
213 protected Vpn(Looper looper, Context context, INetworkManagementService netService,
214 int userHandle, SystemServices systemServices) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700215 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400216 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400217 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400218 mLooper = looper;
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000219 mSystemServices = systemServices;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400220
221 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400222 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700223
224 try {
225 netService.registerObserver(mObserver);
226 } catch (RemoteException e) {
227 Log.wtf(TAG, "Problem registering observer", e);
228 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400229
Chalard Jeandd59ece2017-12-20 13:23:32 +0900230 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0 /* subtype */, NETWORKTYPE,
231 "" /* subtypeName */);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400232 mNetworkCapabilities = new NetworkCapabilities();
233 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
234 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600235 updateCapabilities();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000236
237 loadAlwaysOnPackage();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700238 }
239
Jeff Sharkey57666932013-04-30 17:01:57 -0700240 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +0900241 * Set whether this object is responsible for watching for {@link NetworkInfo}
Jeff Sharkey57666932013-04-30 17:01:57 -0700242 * teardown. When {@code false}, teardown is handled externally by someone
243 * else.
244 */
245 public void setEnableTeardown(boolean enableTeardown) {
246 mEnableTeardown = enableTeardown;
247 }
248
Jeff Sharkey899223b2012-08-04 15:24:58 -0700249 /**
250 * Update current state, dispaching event to listeners.
251 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100252 @VisibleForTesting
253 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700254 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
255 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400256 if (mNetworkAgent != null) {
257 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
258 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100259 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700260 }
261
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600262 public void updateCapabilities() {
263 final Network[] underlyingNetworks = (mConfig != null) ? mConfig.underlyingNetworks : null;
264 updateCapabilities(mContext.getSystemService(ConnectivityManager.class), underlyingNetworks,
265 mNetworkCapabilities);
266
267 if (mNetworkAgent != null) {
268 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
269 }
270 }
271
272 @VisibleForTesting
273 public static void updateCapabilities(ConnectivityManager cm, Network[] underlyingNetworks,
274 NetworkCapabilities caps) {
275 int[] transportTypes = new int[] { NetworkCapabilities.TRANSPORT_VPN };
276 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
277 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
278 boolean metered = false;
279 boolean roaming = false;
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900280 boolean congested = false;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600281
Chalard Jean3bd57052018-05-21 15:30:56 +0900282 boolean hadUnderlyingNetworks = false;
283 if (null != underlyingNetworks) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600284 for (Network underlying : underlyingNetworks) {
285 final NetworkCapabilities underlyingCaps = cm.getNetworkCapabilities(underlying);
Jeff Sharkey4f5e6262018-01-02 11:46:32 -0700286 if (underlyingCaps == null) continue;
Chalard Jean3bd57052018-05-21 15:30:56 +0900287 hadUnderlyingNetworks = true;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600288 for (int underlyingType : underlyingCaps.getTransportTypes()) {
289 transportTypes = ArrayUtils.appendInt(transportTypes, underlyingType);
290 }
291
292 // When we have multiple networks, we have to assume the
293 // worst-case link speed and restrictions.
294 downKbps = NetworkCapabilities.minBandwidth(downKbps,
295 underlyingCaps.getLinkDownstreamBandwidthKbps());
296 upKbps = NetworkCapabilities.minBandwidth(upKbps,
297 underlyingCaps.getLinkUpstreamBandwidthKbps());
298 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
299 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900300 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600301 }
302 }
Chalard Jean3bd57052018-05-21 15:30:56 +0900303 if (!hadUnderlyingNetworks) {
304 // No idea what the underlying networks are; assume sane defaults
305 metered = true;
306 roaming = false;
307 congested = false;
308 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600309
310 caps.setTransportTypes(transportTypes);
311 caps.setLinkDownstreamBandwidthKbps(downKbps);
312 caps.setLinkUpstreamBandwidthKbps(upKbps);
Jeff Sharkey9b2a10f2018-01-17 13:27:03 +0900313 caps.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
314 caps.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
315 caps.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600316 }
317
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700318 /**
Robin Leec3736bc2017-03-10 16:19:54 +0000319 * Chooses whether to force all connections to go though VPN.
320 *
321 * Used to enable/disable legacy VPN lockdown.
322 *
Dan Albertee8e6a02019-01-24 21:05:39 +0000323 * This uses the same ip rule mechanism as {@link #setAlwaysOnPackage(String, boolean)};
324 * previous settings from calling that function will be replaced and saved with the
325 * always-on state.
Robin Leec3736bc2017-03-10 16:19:54 +0000326 *
327 * @param lockdown whether to prevent all traffic outside of a VPN.
328 */
329 public synchronized void setLockdown(boolean lockdown) {
330 enforceControlPermissionOrInternalCaller();
331
332 setVpnForcedLocked(lockdown);
333 mLockdown = lockdown;
334
335 // Update app lockdown setting if it changed. Legacy VPN lockdown status is controlled by
336 // LockdownVpnTracker.isEnabled() which keeps track of its own state.
337 if (mAlwaysOn) {
338 saveAlwaysOnPackage();
339 }
340 }
341
342 /**
junyulai8ed89152018-10-25 10:56:17 +0800343 * Check whether to prevent all traffic outside of a VPN even when the VPN is not connected.
344 *
345 * @return {@code true} if VPN lockdown is enabled.
346 */
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000347 public synchronized boolean getLockdown() {
junyulai8ed89152018-10-25 10:56:17 +0800348 return mLockdown;
349 }
350
351 /**
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000352 * Returns whether VPN is configured as always-on.
353 */
354 public synchronized boolean getAlwaysOn() {
355 return mAlwaysOn;
356 }
357
358 /**
Charles Hea0a87e82017-05-15 17:07:18 +0100359 * Checks if a VPN app supports always-on mode.
360 *
361 * In order to support the always-on feature, an app has to
362 * <ul>
363 * <li>target {@link VERSION_CODES#N API 24} or above, and
Charles He5da5ae32017-08-15 15:30:22 +0100364 * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
365 * meta-data field.
Charles Hea0a87e82017-05-15 17:07:18 +0100366 * </ul>
367 *
368 * @param packageName the canonical package name of the VPN app
369 * @return {@code true} if and only if the VPN app exists and supports always-on mode
370 */
371 public boolean isAlwaysOnPackageSupported(String packageName) {
372 enforceSettingsPermission();
373
374 if (packageName == null) {
375 return false;
376 }
377
378 PackageManager pm = mContext.getPackageManager();
379 ApplicationInfo appInfo = null;
380 try {
381 appInfo = pm.getApplicationInfoAsUser(packageName, 0 /*flags*/, mUserHandle);
382 } catch (NameNotFoundException unused) {
383 Log.w(TAG, "Can't find \"" + packageName + "\" when checking always-on support");
384 }
385 if (appInfo == null || appInfo.targetSdkVersion < VERSION_CODES.N) {
386 return false;
387 }
388
389 final Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
390 intent.setPackage(packageName);
391 List<ResolveInfo> services =
392 pm.queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, mUserHandle);
393 if (services == null || services.size() == 0) {
394 return false;
395 }
396
397 for (ResolveInfo rInfo : services) {
398 final Bundle metaData = rInfo.serviceInfo.metaData;
Charles He5da5ae32017-08-15 15:30:22 +0100399 if (metaData != null &&
400 !metaData.getBoolean(VpnService.SERVICE_META_DATA_SUPPORTS_ALWAYS_ON, true)) {
Charles Hea0a87e82017-05-15 17:07:18 +0100401 return false;
402 }
403 }
404
405 return true;
406 }
407
408 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000409 * Configures an always-on VPN connection through a specific application.
410 * This connection is automatically granted and persisted after a reboot.
411 *
412 * <p>The designated package should exist and declare a {@link VpnService} in its
413 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
414 * otherwise the call will fail.
415 *
Charles Hea0a87e82017-05-15 17:07:18 +0100416 * <p>Note that this method does not check if the VPN app supports always-on mode. The check is
417 * delayed to {@link #startAlwaysOnVpn()}, which is always called immediately after this
418 * method in {@link android.net.IConnectivityManager#setAlwaysOnVpnPackage}.
419 *
Robin Lee17e61832016-05-09 13:46:28 +0100420 * @param packageName the package to designate as always-on VPN supplier.
421 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100422 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000423 */
Dan Albertee8e6a02019-01-24 21:05:39 +0000424 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000425 enforceControlPermissionOrInternalCaller();
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000426
Dan Albertee8e6a02019-01-24 21:05:39 +0000427 if (setAlwaysOnPackageInternal(packageName, lockdown)) {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000428 saveAlwaysOnPackage();
429 return true;
430 }
431 return false;
432 }
433
434 /**
435 * Configures an always-on VPN connection through a specific application, the same as
436 * {@link #setAlwaysOnPackage}.
437 *
438 * Does not perform permission checks. Does not persist any of the changes to storage.
439 *
440 * @param packageName the package to designate as always-on VPN supplier.
441 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
442 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
443 */
444 @GuardedBy("this")
Dan Albertee8e6a02019-01-24 21:05:39 +0000445 private boolean setAlwaysOnPackageInternal(String packageName, boolean lockdown) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100446 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
447 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
448 return false;
449 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000450
Robin Lee244ce8e2016-01-05 18:03:46 +0000451 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100452 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000453 if (!setPackageAuthorization(packageName, true)) {
454 return false;
455 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100456 mAlwaysOn = true;
457 } else {
458 packageName = VpnConfig.LEGACY_VPN;
459 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000460 }
461
Robin Lee17e61832016-05-09 13:46:28 +0100462 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100463 if (isCurrentPreparedPackage(packageName)) {
464 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
465 } else {
466 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100467 prepareInternal(packageName);
468 }
Dan Albertee8e6a02019-01-24 21:05:39 +0000469 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000470 return true;
471 }
472
Robin Lee9ff1a582016-06-10 16:41:10 +0100473 private static boolean isNullOrLegacyVpn(String packageName) {
474 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
475 }
476
Robin Lee244ce8e2016-01-05 18:03:46 +0000477 /**
478 * @return the package name of the VPN controller responsible for always-on VPN,
479 * or {@code null} if none is set or always-on VPN is controlled through
480 * lockdown instead.
Dan Albertee8e6a02019-01-24 21:05:39 +0000481 * @hide
Robin Lee244ce8e2016-01-05 18:03:46 +0000482 */
483 public synchronized String getAlwaysOnPackage() {
484 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100485 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000486 }
487
488 /**
Robin Lee812800c2016-05-13 15:38:08 +0100489 * Save the always-on package and lockdown config into Settings.Secure
490 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000491 @GuardedBy("this")
492 private void saveAlwaysOnPackage() {
Robin Lee812800c2016-05-13 15:38:08 +0100493 final long token = Binder.clearCallingIdentity();
494 try {
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000495 mSystemServices.settingsSecurePutStringForUser(Settings.Secure.ALWAYS_ON_VPN_APP,
Robin Lee812800c2016-05-13 15:38:08 +0100496 getAlwaysOnPackage(), mUserHandle);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000497 mSystemServices.settingsSecurePutIntForUser(Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
Robin Leec3736bc2017-03-10 16:19:54 +0000498 (mAlwaysOn && mLockdown ? 1 : 0), mUserHandle);
Robin Lee812800c2016-05-13 15:38:08 +0100499 } finally {
500 Binder.restoreCallingIdentity(token);
501 }
502 }
503
504 /**
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000505 * Load the always-on package and lockdown config from Settings.Secure
Robin Lee812800c2016-05-13 15:38:08 +0100506 */
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000507 @GuardedBy("this")
508 private void loadAlwaysOnPackage() {
509 final long token = Binder.clearCallingIdentity();
510 try {
511 final String alwaysOnPackage = mSystemServices.settingsSecureGetStringForUser(
512 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
513 final boolean alwaysOnLockdown = mSystemServices.settingsSecureGetIntForUser(
514 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, 0 /*default*/, mUserHandle) != 0;
Dan Albertee8e6a02019-01-24 21:05:39 +0000515 setAlwaysOnPackageInternal(alwaysOnPackage, alwaysOnLockdown);
Robin Leeb8c2a2b2017-03-10 16:17:06 +0000516 } finally {
517 Binder.restoreCallingIdentity(token);
Robin Lee812800c2016-05-13 15:38:08 +0100518 }
519 }
520
521 /**
522 * @return {@code true} if the service was started, the service was already connected, or there
523 * was no always-on VPN to start. {@code false} otherwise.
524 */
525 public boolean startAlwaysOnVpn() {
526 final String alwaysOnPackage;
527 synchronized (this) {
528 alwaysOnPackage = getAlwaysOnPackage();
529 // Skip if there is no service to start.
530 if (alwaysOnPackage == null) {
531 return true;
532 }
Charles Hea0a87e82017-05-15 17:07:18 +0100533 // Remove always-on VPN if it's not supported.
534 if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
Dan Albertee8e6a02019-01-24 21:05:39 +0000535 setAlwaysOnPackage(null, false);
Charles Hea0a87e82017-05-15 17:07:18 +0100536 return false;
537 }
Robin Lee812800c2016-05-13 15:38:08 +0100538 // Skip if the service is already established. This isn't bulletproof: it's not bound
539 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
540 // which may restart the connection.
541 if (getNetworkInfo().isConnected()) {
542 return true;
543 }
544 }
545
Christopher Tatee0be7e82017-02-08 17:38:20 -0800546 // Tell the OS that background services in this app need to be allowed for
547 // a short time, so we can bootstrap the VPN service.
548 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100549 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800550 DeviceIdleController.LocalService idleController =
551 LocalServices.getService(DeviceIdleController.LocalService.class);
552 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900553 VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");
Christopher Tatee0be7e82017-02-08 17:38:20 -0800554
555 // Start the VPN service declared in the app's manifest.
556 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
557 serviceIntent.setPackage(alwaysOnPackage);
558 try {
559 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
560 } catch (RuntimeException e) {
561 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
562 return false;
563 }
564 } finally {
565 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100566 }
567 }
568
569 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700570 * Prepare for a VPN application. This method is designed to solve
571 * race conditions. It first compares the current prepared package
572 * with {@code oldPackage}. If they are the same, the prepared
573 * package is revoked and replaced with {@code newPackage}. If
574 * {@code oldPackage} is {@code null}, the comparison is omitted.
575 * If {@code newPackage} is the same package or {@code null}, the
576 * revocation is omitted. This method returns {@code true} if the
577 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700578 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700579 * Legacy VPN is handled specially since it is not a real package.
580 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
581 * it can be revoked by itself.
582 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900583 * Note: when we added VPN pre-consent in
584 * https://android.googlesource.com/platform/frameworks/base/+/0554260
585 * the names oldPackage and newPackage became misleading, because when
586 * an app is pre-consented, we actually prepare oldPackage, not newPackage.
Victor Chang98a633a2016-05-27 17:30:49 +0100587 *
588 * Their meanings actually are:
589 *
590 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
591 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100592 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100593 * and revoke any current app VPN and re-prepare legacy vpn.
594 *
Robin Lee812800c2016-05-13 15:38:08 +0100595 * TODO: Rename the variables - or split this method into two - and end this confusion.
596 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
597 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100598 *
599 * @param oldPackage The package name of the old VPN application
600 * @param newPackage The package name of the new VPN application
601 *
Chalard Jeandd59ece2017-12-20 13:23:32 +0900602 * @return true if the operation succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700603 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700604 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700605 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100606 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100607 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100608 return false;
609 }
610
Chalard Jeandd59ece2017-12-20 13:23:32 +0900611 // Package is not the same or old package was reinstalled.
Victor Chang98a633a2016-05-27 17:30:49 +0100612 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700613 // The package doesn't match. We return false (to obtain user consent) unless the
614 // user has already consented to that VPN package.
615 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
616 prepareInternal(oldPackage);
617 return true;
618 }
619 return false;
620 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
621 && !isVpnUserPreConsented(oldPackage)) {
622 // Currently prepared VPN is revoked, so unprepare it and return false.
623 prepareInternal(VpnConfig.LEGACY_VPN);
624 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700625 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700626 }
627
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700628 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700629 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100630 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700631 return true;
632 }
633
Robin Lee1b1bcd72016-02-12 18:11:30 +0000634 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700635 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700636
Victor Chang98a633a2016-05-27 17:30:49 +0100637 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100638 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100639 return false;
640 }
641
Jeff Davidson11008a72014-11-20 13:12:46 -0800642 prepareInternal(newPackage);
643 return true;
644 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700645
Victor Chang98a633a2016-05-27 17:30:49 +0100646 private boolean isCurrentPreparedPackage(String packageName) {
647 // We can't just check that packageName matches mPackage, because if the app was uninstalled
648 // and reinstalled it will no longer be prepared. Instead check the UID.
649 return getAppUid(packageName, mUserHandle) == mOwnerUID;
650 }
651
Jeff Davidson11008a72014-11-20 13:12:46 -0800652 /** Prepare the VPN for the given package. Does not perform permission checks. */
653 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400654 long token = Binder.clearCallingIdentity();
655 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800656 // Reset the interface.
657 if (mInterface != null) {
658 mStatusIntent = null;
659 agentDisconnect();
660 jniReset(mInterface);
661 mInterface = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900662 mNetworkCapabilities.setUids(null);
Jeff Davidson11008a72014-11-20 13:12:46 -0800663 }
664
665 // Revoke the connection or stop LegacyVpnRunner.
666 if (mConnection != null) {
667 try {
668 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
669 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
670 } catch (Exception e) {
671 // ignore
672 }
673 mContext.unbindService(mConnection);
674 mConnection = null;
675 } else if (mLegacyVpnRunner != null) {
676 mLegacyVpnRunner.exit();
677 mLegacyVpnRunner = null;
678 }
679
680 try {
681 mNetd.denyProtect(mOwnerUID);
682 } catch (Exception e) {
683 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
684 }
685
686 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
687 mPackage = newPackage;
688 mOwnerUID = getAppUid(newPackage, mUserHandle);
689 try {
690 mNetd.allowProtect(mOwnerUID);
691 } catch (Exception e) {
692 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
693 }
694 mConfig = null;
695
696 updateState(DetailedState.IDLE, "prepare");
Robin Leec3736bc2017-03-10 16:19:54 +0000697 setVpnForcedLocked(mLockdown);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400698 } finally {
699 Binder.restoreCallingIdentity(token);
700 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700701 }
702
Jeff Davidson05542602014-08-11 14:07:27 -0700703 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100704 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700705 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000706 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700707 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000708 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700709
Robin Lee3b3dd942015-05-12 18:14:58 +0100710 int uid = getAppUid(packageName, mUserHandle);
711 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
712 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000713 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700714 }
715
716 long token = Binder.clearCallingIdentity();
717 try {
718 AppOpsManager appOps =
719 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100720 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700721 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000722 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700723 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100724 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700725 } finally {
726 Binder.restoreCallingIdentity(token);
727 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000728 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700729 }
730
731 private boolean isVpnUserPreConsented(String packageName) {
732 AppOpsManager appOps =
733 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
734
735 // Verify that the caller matches the given package and has permission to activate VPNs.
736 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
737 packageName) == AppOpsManager.MODE_ALLOWED;
738 }
739
Paul Jensen0784eea2014-08-19 16:00:24 -0400740 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700741 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400742 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700743 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400744 PackageManager pm = mContext.getPackageManager();
745 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700746 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700747 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400748 } catch (NameNotFoundException e) {
749 result = -1;
750 }
751 return result;
752 }
753
754 public NetworkInfo getNetworkInfo() {
755 return mNetworkInfo;
756 }
757
Paul Jensen31a94f42015-02-13 14:18:39 -0500758 public int getNetId() {
759 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
760 }
761
Lorenzo Colitti60446162014-09-20 00:14:31 +0900762 private LinkProperties makeLinkProperties() {
763 boolean allowIPv4 = mConfig.allowIPv4;
764 boolean allowIPv6 = mConfig.allowIPv6;
765
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400766 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900767
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400768 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700769
Lorenzo Colitti60446162014-09-20 00:14:31 +0900770 if (mConfig.addresses != null) {
771 for (LinkAddress address : mConfig.addresses) {
772 lp.addLinkAddress(address);
773 allowIPv4 |= address.getAddress() instanceof Inet4Address;
774 allowIPv6 |= address.getAddress() instanceof Inet6Address;
775 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400776 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900777
778 if (mConfig.routes != null) {
779 for (RouteInfo route : mConfig.routes) {
780 lp.addRoute(route);
781 InetAddress address = route.getDestination().getAddress();
782 allowIPv4 |= address instanceof Inet4Address;
783 allowIPv6 |= address instanceof Inet6Address;
784 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400785 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700786
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400787 if (mConfig.dnsServers != null) {
788 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700789 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
790 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900791 allowIPv4 |= address instanceof Inet4Address;
792 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400793 }
794 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700795
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000796 lp.setHttpProxy(mConfig.proxyInfo);
797
Lorenzo Colitti60446162014-09-20 00:14:31 +0900798 if (!allowIPv4) {
799 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
800 }
801 if (!allowIPv6) {
802 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
803 }
804
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400805 // Concatenate search domains into a string.
806 StringBuilder buffer = new StringBuilder();
807 if (mConfig.searchDomains != null) {
808 for (String domain : mConfig.searchDomains) {
809 buffer.append(domain).append(' ');
810 }
811 }
812 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700813
Lorenzo Colitti60446162014-09-20 00:14:31 +0900814 // TODO: Stop setting the MTU in jniCreate and set it here.
815
816 return lp;
817 }
818
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900819 /**
820 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
821 *
822 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
823 * space or to most of the IPv6 address space, where "most" is defined by the value of the
824 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
825 * by any of the routes, then it's decided that most of the space is routed.
826 * @hide
827 */
828 @VisibleForTesting
829 static boolean providesRoutesToMostDestinations(LinkProperties lp) {
Chalard Jeane0d26f62018-03-29 14:10:44 +0900830 final List<RouteInfo> routes = lp.getAllRoutes();
831 if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900832 final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
833 TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
834 TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
Chalard Jeane0d26f62018-03-29 14:10:44 +0900835 for (final RouteInfo route : routes) {
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900836 IpPrefix destination = route.getDestination();
837 if (destination.isIPv4()) {
838 ipv4Prefixes.add(destination);
839 } else {
840 ipv6Prefixes.add(destination);
841 }
842 }
843 if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
844 return true;
845 }
846 return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
847 .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
848 }
849
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +0900850 /**
851 * Attempt to perform a seamless handover of VPNs by only updating LinkProperties without
852 * registering a new NetworkAgent. This is not always possible if the new VPN configuration
853 * has certain changes, in which case this method would just return {@code false}.
854 */
855 private boolean updateLinkPropertiesInPlaceIfPossible(NetworkAgent agent, VpnConfig oldConfig) {
856 // NetworkMisc cannot be updated without registering a new NetworkAgent.
857 if (oldConfig.allowBypass != mConfig.allowBypass) {
858 Log.i(TAG, "Handover not possible due to changes to allowBypass");
859 return false;
860 }
861
862 // TODO: we currently do not support seamless handover if the allowed or disallowed
863 // applications have changed. Consider diffing UID ranges and only applying the delta.
864 if (!Objects.equals(oldConfig.allowedApplications, mConfig.allowedApplications) ||
865 !Objects.equals(oldConfig.disallowedApplications, mConfig.disallowedApplications)) {
866 Log.i(TAG, "Handover not possible due to changes to whitelisted/blacklisted apps");
867 return false;
868 }
869
870 LinkProperties lp = makeLinkProperties();
871 final boolean hadInternetCapability = mNetworkCapabilities.hasCapability(
872 NetworkCapabilities.NET_CAPABILITY_INTERNET);
873 final boolean willHaveInternetCapability = providesRoutesToMostDestinations(lp);
874 if (hadInternetCapability != willHaveInternetCapability) {
875 // A seamless handover would have led to a change to INTERNET capability, which
876 // is supposed to be immutable for a given network. In this case bail out and do not
877 // perform handover.
878 Log.i(TAG, "Handover not possible due to changes to INTERNET capability");
879 return false;
880 }
881
882 agent.sendLinkProperties(lp);
883 return true;
884 }
885
Lorenzo Colitti60446162014-09-20 00:14:31 +0900886 private void agentConnect() {
887 LinkProperties lp = makeLinkProperties();
888
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900889 if (providesRoutesToMostDestinations(lp)) {
Lorenzo Colitti60446162014-09-20 00:14:31 +0900890 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
891 } else {
892 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
893 }
894
Robin Lee323f29d2016-05-04 16:38:06 +0100895 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700896
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700897 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100898 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700899
Chalard Jeanf474fc32018-01-17 15:10:05 +0900900 mNetworkCapabilities.setEstablishingVpnAppUid(Binder.getCallingUid());
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900901 mNetworkCapabilities.setUids(createUserAndRestrictedProfilesRanges(mUserHandle,
902 mConfig.allowedApplications, mConfig.disallowedApplications));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400903 long token = Binder.clearCallingIdentity();
904 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900905 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE /* logtag */,
Chalard Jeandda156a2018-01-10 21:19:32 +0900906 mNetworkInfo, mNetworkCapabilities, lp,
907 ConnectivityConstants.VPN_DEFAULT_SCORE, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700908 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400909 public void unwanted() {
910 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700911 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400912 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700913 } finally {
914 Binder.restoreCallingIdentity(token);
915 }
Robin Lee323f29d2016-05-04 16:38:06 +0100916 mNetworkInfo.setIsAvailable(true);
917 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400918 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700919
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700920 private boolean canHaveRestrictedProfile(int userId) {
921 long token = Binder.clearCallingIdentity();
922 try {
923 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
924 } finally {
925 Binder.restoreCallingIdentity(token);
926 }
927 }
928
Tony Mak1a405fe2016-06-30 11:19:20 +0100929 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400930 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100931 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
932 networkInfo.setIsAvailable(false);
933 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400934 networkAgent.sendNetworkInfo(networkInfo);
935 }
936 }
937
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400938 private void agentDisconnect() {
939 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100940 mNetworkInfo.setIsAvailable(false);
941 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400942 mNetworkAgent = null;
943 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700944 }
945
946 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700947 * Establish a VPN network and return the file descriptor of the VPN
948 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700949 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700950 *
951 * @param config The parameters to configure the network.
952 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700953 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700954 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700955 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700956 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400957 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700958 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700959 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700960 // Check to ensure consent hasn't been revoked since we were prepared.
961 if (!isVpnUserPreConsented(mPackage)) {
962 return null;
963 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700964 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700965 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
966 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700967 long token = Binder.clearCallingIdentity();
968 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700969 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400970 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100971 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700972 throw new SecurityException("Restricted users cannot establish VPNs");
973 }
974
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700975 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Chalard Jeandd59ece2017-12-20 13:23:32 +0900976 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700977 if (info == null) {
978 throw new SecurityException("Cannot find " + config.user);
979 }
980 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
981 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
982 }
983 } catch (RemoteException e) {
Chalard Jeandd59ece2017-12-20 13:23:32 +0900984 throw new SecurityException("Cannot find " + config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700985 } finally {
986 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700987 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700988
Chad Brubaker850eb672014-03-21 21:02:47 +0000989 // Save the old config in case we need to go back.
990 VpnConfig oldConfig = mConfig;
991 String oldInterface = mInterface;
992 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400993 NetworkAgent oldNetworkAgent = mNetworkAgent;
Chalard Jeanecacd5e2017-12-27 14:23:31 +0900994 Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
Chad Brubaker850eb672014-03-21 21:02:47 +0000995
Chia-chi Yehe9107902011-07-02 01:48:50 -0700996 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700997 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700998 try {
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700999 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001000
Chad Brubakerc2865192013-07-10 14:46:23 -07001001 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001002 StringBuilder builder = new StringBuilder();
1003 for (LinkAddress address : config.addresses) {
1004 builder.append(" " + address);
1005 }
1006 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001007 throw new IllegalArgumentException("At least one address must be specified");
1008 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001009 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001010 if (!mContext.bindServiceAsUser(intent, connection,
1011 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1012 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001013 throw new IllegalStateException("Cannot bind " + config.user);
1014 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001015
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001016 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001017 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001018
1019 // Fill more values.
1020 config.user = mPackage;
1021 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -07001022 config.startTime = SystemClock.elapsedRealtime();
1023 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +00001024
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001025 // Set up forwarding and DNS rules.
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001026 // First attempt to do a seamless handover that only changes the interface name and
1027 // parameters. If that fails, disconnect.
1028 if (oldConfig != null
1029 && updateLinkPropertiesInPlaceIfPossible(mNetworkAgent, oldConfig)) {
1030 // Keep mNetworkAgent unchanged
1031 } else {
1032 mNetworkAgent = null;
1033 updateState(DetailedState.CONNECTING, "establish");
1034 // Set up forwarding and DNS rules.
1035 agentConnect();
1036 // Remove the old tun's user forwarding rules
1037 // The new tun's user rules have already been added above so they will take over
1038 // as rules are deleted. This prevents data leakage as the rules are moved over.
1039 agentDisconnect(oldNetworkAgent);
1040 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001041
1042 if (oldConnection != null) {
1043 mContext.unbindService(oldConnection);
1044 }
Lorenzo Colitti6fd62b32017-09-22 21:27:32 +09001045
Chad Brubaker850eb672014-03-21 21:02:47 +00001046 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001047 jniReset(oldInterface);
1048 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -07001049
1050 try {
1051 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
1052 } catch (IOException e) {
1053 throw new IllegalStateException(
1054 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
1055 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001056 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +00001057 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001058 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +00001059 // restore old state
1060 mConfig = oldConfig;
1061 mConnection = oldConnection;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001062 mNetworkCapabilities.setUids(oldUsers);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001063 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +00001064 mInterface = oldInterface;
1065 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -07001066 }
Chad Brubaker850eb672014-03-21 21:02:47 +00001067 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001068 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001069 }
1070
Chad Brubakerc2865192013-07-10 14:46:23 -07001071 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001072 return mNetworkAgent != null && mInterface != null;
1073 }
1074
1075 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
1076 // that a call to mutate VPN state is admissible.
Chalard Jeanf666d0a2018-05-18 21:47:45 +09001077 @VisibleForTesting
1078 protected boolean isCallerEstablishedOwnerLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001079 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -07001080 }
1081
Paul Jensen0784eea2014-08-19 16:00:24 -04001082 // Note: Return type guarantees results are deduped and sorted, which callers require.
1083 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
1084 SortedSet<Integer> uids = new TreeSet<Integer>();
1085 for (String app : packageNames) {
1086 int uid = getAppUid(app, userHandle);
1087 if (uid != -1) uids.add(uid);
1088 }
1089 return uids;
1090 }
1091
Robin Lee4d03abc2016-05-09 12:32:27 +01001092 /**
1093 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
1094 * associated with one user, and any restricted profiles attached to that user.
1095 *
1096 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1097 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1098 * in each user and profile will be included.
1099 *
1100 * @param userHandle The userId to create UID ranges for along with any of its restricted
1101 * profiles.
1102 * @param allowedApplications (optional) whitelist of applications to include.
1103 * @param disallowedApplications (optional) blacklist of applications to exclude.
1104 */
1105 @VisibleForTesting
1106 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
1107 @Nullable List<String> allowedApplications,
1108 @Nullable List<String> disallowedApplications) {
1109 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -07001110
Robin Lee4d03abc2016-05-09 12:32:27 +01001111 // Assign the top-level user to the set of ranges
1112 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
1113
1114 // If the user can have restricted profiles, assign all its restricted profiles too
1115 if (canHaveRestrictedProfile(userHandle)) {
1116 final long token = Binder.clearCallingIdentity();
1117 List<UserInfo> users;
1118 try {
Robin Lee17e61832016-05-09 13:46:28 +01001119 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +01001120 } finally {
1121 Binder.restoreCallingIdentity(token);
1122 }
1123 for (UserInfo user : users) {
1124 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
1125 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
1126 }
1127 }
1128 }
1129 return ranges;
1130 }
1131
1132 /**
1133 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
1134 * associated with one user.
1135 *
1136 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
1137 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
1138 * in the user will be included.
1139 *
1140 * @param ranges {@link Set} of {@link UidRange}s to which to add.
1141 * @param userHandle The userId to add to {@param ranges}.
1142 * @param allowedApplications (optional) whitelist of applications to include.
1143 * @param disallowedApplications (optional) blacklist of applications to exclude.
1144 */
1145 @VisibleForTesting
1146 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
1147 @Nullable List<String> allowedApplications,
1148 @Nullable List<String> disallowedApplications) {
1149 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001150 // Add ranges covering all UIDs for allowedApplications.
1151 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +01001152 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001153 if (start == -1) {
1154 start = uid;
1155 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001156 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001157 start = uid;
1158 }
1159 stop = uid;
1160 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001161 if (start != -1) ranges.add(new UidRange(start, stop));
1162 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001163 // Add all ranges for user skipping UIDs for disallowedApplications.
1164 final UidRange userRange = UidRange.createForUser(userHandle);
1165 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +01001166 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001167 if (uid == start) {
1168 start++;
1169 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +01001170 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -04001171 start = uid + 1;
1172 }
1173 }
Robin Lee4d03abc2016-05-09 12:32:27 +01001174 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -04001175 } else {
1176 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +01001177 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -04001178 }
Chad Brubakerc2865192013-07-10 14:46:23 -07001179 }
1180
Paul Jensen0784eea2014-08-19 16:00:24 -04001181 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
1182 // apply to userHandle.
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001183 static private List<UidRange> uidRangesForUser(int userHandle, Set<UidRange> existingRanges) {
1184 // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
1185 // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
Paul Jensen0784eea2014-08-19 16:00:24 -04001186 final UidRange userRange = UidRange.createForUser(userHandle);
1187 final List<UidRange> ranges = new ArrayList<UidRange>();
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001188 for (UidRange range : existingRanges) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001189 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -04001190 ranges.add(range);
1191 }
1192 }
1193 return ranges;
1194 }
1195
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001196 public void onUserAdded(int userHandle) {
1197 // If the user is restricted tie them to the parent user's VPN
1198 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001199 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001200 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001201 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1202 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001203 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001204 addUserToRanges(existingRanges, userHandle, mConfig.allowedApplications,
Robin Lee17e61832016-05-09 13:46:28 +01001205 mConfig.disallowedApplications);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001206 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001207 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001208 } catch (Exception e) {
1209 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001210 }
Robin Lee17e61832016-05-09 13:46:28 +01001211 }
Robin Leec3736bc2017-03-10 16:19:54 +00001212 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001213 }
1214 }
1215 }
1216
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001217 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001218 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001219 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001220 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001221 synchronized(Vpn.this) {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001222 final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
1223 if (existingRanges != null) {
Robin Lee17e61832016-05-09 13:46:28 +01001224 try {
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001225 final List<UidRange> removedRanges =
1226 uidRangesForUser(userHandle, existingRanges);
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001227 existingRanges.removeAll(removedRanges);
1228 mNetworkCapabilities.setUids(existingRanges);
Chalard Jeanf213ca12018-01-16 18:43:05 +09001229 updateCapabilities();
Robin Lee17e61832016-05-09 13:46:28 +01001230 } catch (Exception e) {
1231 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1232 }
1233 }
Robin Leec3736bc2017-03-10 16:19:54 +00001234 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001235 }
1236 }
1237 }
1238
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001239 /**
Robin Lee17e61832016-05-09 13:46:28 +01001240 * Called when the user associated with this VPN has just been stopped.
1241 */
1242 public synchronized void onUserStopped() {
1243 // Switch off networking lockdown (if it was enabled)
Robin Leec3736bc2017-03-10 16:19:54 +00001244 setLockdown(false);
Robin Lee17e61832016-05-09 13:46:28 +01001245 mAlwaysOn = false;
1246
1247 // Quit any active connections
1248 agentDisconnect();
1249 }
1250
1251 /**
Dan Albertee8e6a02019-01-24 21:05:39 +00001252 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1253 * service app itself, to only sockets that have had {@code protect()} called on them. All
1254 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
Robin Lee17e61832016-05-09 13:46:28 +01001255 *
1256 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1257 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1258 *
1259 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1260 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1261 *
1262 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1263 * {@link Vpn} goes through a VPN connection or is blocked until one is
1264 * available, {@code false} to lift the requirement.
1265 *
1266 * @see #mBlockedUsers
1267 */
1268 @GuardedBy("this")
1269 private void setVpnForcedLocked(boolean enforce) {
Dan Albertee8e6a02019-01-24 21:05:39 +00001270 final List<String> exemptedPackages =
1271 isNullOrLegacyVpn(mPackage) ? null : Collections.singletonList(mPackage);
Robin Lee17e61832016-05-09 13:46:28 +01001272 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
Robin Leec3736bc2017-03-10 16:19:54 +00001273
1274 Set<UidRange> addedRanges = Collections.emptySet();
Robin Lee17e61832016-05-09 13:46:28 +01001275 if (enforce) {
Robin Leec3736bc2017-03-10 16:19:54 +00001276 addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
Robin Lee17e61832016-05-09 13:46:28 +01001277 /* allowedApplications */ null,
Robin Leec3736bc2017-03-10 16:19:54 +00001278 /* disallowedApplications */ exemptedPackages);
Robin Lee17e61832016-05-09 13:46:28 +01001279
Bernie Innocenti00000fe2018-05-28 22:04:37 +09001280 // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
1281 // directly from the kernel and is marked as uid=0. So we adjust the range to allow
1282 // it through (b/69873852).
1283 for (UidRange range : addedRanges) {
1284 if (range.start == 0) {
1285 addedRanges.remove(range);
1286 if (range.stop != 0) {
1287 addedRanges.add(new UidRange(1, range.stop));
1288 }
1289 }
1290 }
1291
Robin Lee17e61832016-05-09 13:46:28 +01001292 removedRanges.removeAll(addedRanges);
1293 addedRanges.removeAll(mBlockedUsers);
Robin Lee17e61832016-05-09 13:46:28 +01001294 }
Robin Leec3736bc2017-03-10 16:19:54 +00001295
1296 setAllowOnlyVpnForUids(false, removedRanges);
1297 setAllowOnlyVpnForUids(true, addedRanges);
Robin Lee17e61832016-05-09 13:46:28 +01001298 }
1299
1300 /**
1301 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1302 * to make connections through sockets that have had {@code protect()} called on them.
1303 *
1304 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1305 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1306 * {@code true}) or to remove.
1307 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1308 * including added ranges that already existed or removed ones that didn't.
1309 */
1310 @GuardedBy("this")
1311 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1312 if (ranges.size() == 0) {
1313 return true;
1314 }
1315 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1316 try {
1317 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1318 } catch (RemoteException | RuntimeException e) {
1319 Log.e(TAG, "Updating blocked=" + enforce
1320 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1321 return false;
1322 }
1323 if (enforce) {
1324 mBlockedUsers.addAll(ranges);
1325 } else {
1326 mBlockedUsers.removeAll(ranges);
1327 }
1328 return true;
1329 }
1330
1331 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001332 * Return the configuration of the currently running VPN.
1333 */
1334 public VpnConfig getVpnConfig() {
1335 enforceControlPermission();
1336 return mConfig;
1337 }
1338
Jeff Sharkey899223b2012-08-04 15:24:58 -07001339 @Deprecated
1340 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1341 try {
1342 mObserver.interfaceStatusChanged(iface, up);
1343 } catch (RemoteException e) {
1344 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001345 }
1346 }
1347
Jeff Sharkey899223b2012-08-04 15:24:58 -07001348 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1349 @Override
1350 public void interfaceStatusChanged(String interfaze, boolean up) {
1351 synchronized (Vpn.this) {
1352 if (!up && mLegacyVpnRunner != null) {
1353 mLegacyVpnRunner.check(interfaze);
1354 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001355 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001356 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001357
Jeff Sharkey899223b2012-08-04 15:24:58 -07001358 @Override
1359 public void interfaceRemoved(String interfaze) {
1360 synchronized (Vpn.this) {
1361 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001362 mStatusIntent = null;
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001363 mNetworkCapabilities.setUids(null);
Paul Jensenc4c72312014-12-08 14:04:51 -05001364 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001365 mInterface = null;
1366 if (mConnection != null) {
1367 mContext.unbindService(mConnection);
1368 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001369 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001370 } else if (mLegacyVpnRunner != null) {
1371 mLegacyVpnRunner.exit();
1372 mLegacyVpnRunner = null;
1373 }
1374 }
1375 }
1376 }
1377 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001378
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001379 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001380 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001381 }
1382
Robin Lee244ce8e2016-01-05 18:03:46 +00001383 private void enforceControlPermissionOrInternalCaller() {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001384 // Require the caller to be either an application with CONTROL_VPN permission or a process
Robin Lee244ce8e2016-01-05 18:03:46 +00001385 // in the system server.
1386 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1387 "Unauthorized Caller");
1388 }
1389
Charles Hea0a87e82017-05-15 17:07:18 +01001390 private void enforceSettingsPermission() {
1391 mContext.enforceCallingOrSelfPermission(Manifest.permission.NETWORK_SETTINGS,
1392 "Unauthorized Caller");
1393 }
1394
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001395 private class Connection implements ServiceConnection {
1396 private IBinder mService;
1397
1398 @Override
1399 public void onServiceConnected(ComponentName name, IBinder service) {
1400 mService = service;
1401 }
1402
1403 @Override
1404 public void onServiceDisconnected(ComponentName name) {
1405 mService = null;
1406 }
1407 }
1408
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001409 private void prepareStatusIntent() {
1410 final long token = Binder.clearCallingIdentity();
1411 try {
1412 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1413 } finally {
1414 Binder.restoreCallingIdentity(token);
1415 }
1416 }
1417
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001418 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001419 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001420 return false;
1421 }
1422 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001423 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001424 return success;
1425 }
1426
1427 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001428 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001429 return false;
1430 }
1431 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001432 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001433 return success;
1434 }
1435
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001436 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1437 if (!isCallerEstablishedOwnerLocked()) {
1438 return false;
1439 }
1440 if (networks == null) {
1441 mConfig.underlyingNetworks = null;
1442 } else {
1443 mConfig.underlyingNetworks = new Network[networks.length];
1444 for (int i = 0; i < networks.length; ++i) {
1445 if (networks[i] == null) {
1446 mConfig.underlyingNetworks[i] = null;
1447 } else {
1448 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1449 }
1450 }
1451 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06001452 updateCapabilities();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001453 return true;
1454 }
1455
1456 public synchronized Network[] getUnderlyingNetworks() {
1457 if (!isRunningLocked()) {
1458 return null;
1459 }
1460 return mConfig.underlyingNetworks;
1461 }
1462
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001463 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09001464 * This method should only be called by ConnectivityService because it doesn't
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001465 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1466 */
1467 public synchronized VpnInfo getVpnInfo() {
1468 if (!isRunningLocked()) {
1469 return null;
1470 }
1471
1472 VpnInfo info = new VpnInfo();
1473 info.ownerUid = mOwnerUID;
1474 info.vpnIface = mInterface;
1475 return info;
1476 }
1477
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001478 public synchronized boolean appliesToUid(int uid) {
1479 if (!isRunningLocked()) {
1480 return false;
1481 }
Chalard Jeanecacd5e2017-12-27 14:23:31 +09001482 return mNetworkCapabilities.appliesToUid(uid);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001483 }
1484
Robin Lee17e61832016-05-09 13:46:28 +01001485 /**
junyulai8ed89152018-10-25 10:56:17 +08001486 * @param uid The target uid.
Robin Lee17e61832016-05-09 13:46:28 +01001487 *
junyulai8ed89152018-10-25 10:56:17 +08001488 * @return {@code true} if {@code uid} is included in one of the mBlockedUsers ranges and the
1489 * VPN is not connected, or if the VPN is connected but does not apply to the {@code uid}.
1490 *
1491 * @apiNote This method don't check VPN lockdown status.
Robin Lee17e61832016-05-09 13:46:28 +01001492 * @see #mBlockedUsers
1493 */
1494 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001495 if (mNetworkInfo.isConnected()) {
1496 return !appliesToUid(uid);
1497 } else {
1498 for (UidRange uidRange : mBlockedUsers) {
1499 if (uidRange.contains(uid)) {
1500 return true;
1501 }
1502 }
1503 return false;
1504 }
Robin Lee17e61832016-05-09 13:46:28 +01001505 }
1506
Tony Mak1a405fe2016-06-30 11:19:20 +01001507 private void updateAlwaysOnNotification(DetailedState networkState) {
1508 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
Tony Mak1a405fe2016-06-30 11:19:20 +01001509
Tony Mak1a405fe2016-06-30 11:19:20 +01001510 final UserHandle user = UserHandle.of(mUserHandle);
1511 final long token = Binder.clearCallingIdentity();
1512 try {
1513 final NotificationManager notificationManager = NotificationManager.from(mContext);
1514 if (!visible) {
Charles He15297a62017-04-08 22:03:42 +01001515 notificationManager.cancelAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED, user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001516 return;
1517 }
Charles Heab6f2f62017-07-12 15:30:00 +01001518 final Intent intent = new Intent();
1519 intent.setComponent(ComponentName.unflattenFromString(mContext.getString(
1520 R.string.config_customVpnAlwaysOnDisconnectedDialogComponent)));
1521 intent.putExtra("lockdown", mLockdown);
1522 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001523 final PendingIntent configIntent = mSystemServices.pendingIntentGetActivityAsUser(
1524 intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001525 final Notification.Builder builder =
1526 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1527 .setSmallIcon(R.drawable.vpn_connected)
1528 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1529 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1530 .setContentIntent(configIntent)
1531 .setCategory(Notification.CATEGORY_SYSTEM)
1532 .setVisibility(Notification.VISIBILITY_PUBLIC)
1533 .setOngoing(true)
1534 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001535 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1536 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001537 } finally {
1538 Binder.restoreCallingIdentity(token);
1539 }
1540 }
1541
Robin Leeb8c2a2b2017-03-10 16:17:06 +00001542 /**
1543 * Facade for system service calls that change, or depend on, state outside of
1544 * {@link ConnectivityService} and have hard-to-mock interfaces.
1545 *
1546 * @see com.android.server.connectivity.VpnTest
1547 */
1548 @VisibleForTesting
1549 public static class SystemServices {
1550 private final Context mContext;
1551
1552 public SystemServices(@NonNull Context context) {
1553 mContext = context;
1554 }
1555
1556 /**
1557 * @see PendingIntent#getActivityAsUser()
1558 */
1559 public PendingIntent pendingIntentGetActivityAsUser(
1560 Intent intent, int flags, UserHandle user) {
1561 return PendingIntent.getActivityAsUser(mContext, 0 /*request*/, intent, flags,
1562 null /*options*/, user);
1563 }
1564
1565 /**
1566 * @see Settings.Secure#putStringForUser
1567 */
1568 public void settingsSecurePutStringForUser(String key, String value, int userId) {
1569 Settings.Secure.putStringForUser(mContext.getContentResolver(), key, value, userId);
1570 }
1571
1572 /**
1573 * @see Settings.Secure#putIntForUser
1574 */
1575 public void settingsSecurePutIntForUser(String key, int value, int userId) {
1576 Settings.Secure.putIntForUser(mContext.getContentResolver(), key, value, userId);
1577 }
1578
1579 /**
1580 * @see Settings.Secure#getStringForUser
1581 */
1582 public String settingsSecureGetStringForUser(String key, int userId) {
1583 return Settings.Secure.getStringForUser(mContext.getContentResolver(), key, userId);
1584 }
1585
1586 /**
1587 * @see Settings.Secure#getIntForUser
1588 */
1589 public int settingsSecureGetIntForUser(String key, int def, int userId) {
1590 return Settings.Secure.getIntForUser(mContext.getContentResolver(), key, def, userId);
1591 }
1592 }
1593
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001594 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001595 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001596 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001597 private native void jniReset(String interfaze);
1598 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001599 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1600 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001601
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001602 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1603 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001604 // Currently legacy VPN only works on IPv4.
1605 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001606 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001607 }
1608 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001609
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001610 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001611 }
1612
1613 /**
1614 * Start legacy VPN, controlling native daemons as needed. Creates a
1615 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001616 *
1617 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1618 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1619 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001620 */
1621 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001622 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001623 long token = Binder.clearCallingIdentity();
1624 try {
1625 startLegacyVpnPrivileged(profile, keyStore, egress);
1626 } finally {
1627 Binder.restoreCallingIdentity(token);
1628 }
1629 }
1630
1631 /**
1632 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1633 * permissions under the assumption that the caller is the system.
1634 *
1635 * Callers are responsible for checking permissions if needed.
1636 */
1637 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1638 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001639 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001640 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001641 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1642 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001643 throw new SecurityException("Restricted users cannot establish VPNs");
1644 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001645
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001646 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1647 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1648 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001649
1650 // Load certificates.
1651 String privateKey = "";
1652 String userCert = "";
1653 String caCert = "";
1654 String serverCert = "";
1655 if (!profile.ipsecUserCert.isEmpty()) {
1656 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1657 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001658 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001659 }
1660 if (!profile.ipsecCaCert.isEmpty()) {
1661 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001662 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001663 }
1664 if (!profile.ipsecServerCert.isEmpty()) {
1665 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001666 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001667 }
1668 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1669 throw new IllegalStateException("Cannot load credentials");
1670 }
1671
1672 // Prepare arguments for racoon.
1673 String[] racoon = null;
1674 switch (profile.type) {
1675 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1676 racoon = new String[] {
1677 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1678 profile.ipsecSecret, "1701",
1679 };
1680 break;
1681 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1682 racoon = new String[] {
1683 iface, profile.server, "udprsa", privateKey, userCert,
1684 caCert, serverCert, "1701",
1685 };
1686 break;
1687 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1688 racoon = new String[] {
1689 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1690 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1691 };
1692 break;
1693 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1694 racoon = new String[] {
1695 iface, profile.server, "xauthrsa", privateKey, userCert,
1696 caCert, serverCert, profile.username, profile.password, "", gateway,
1697 };
1698 break;
1699 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1700 racoon = new String[] {
1701 iface, profile.server, "hybridrsa",
1702 caCert, serverCert, profile.username, profile.password, "", gateway,
1703 };
1704 break;
1705 }
1706
1707 // Prepare arguments for mtpd.
1708 String[] mtpd = null;
1709 switch (profile.type) {
1710 case VpnProfile.TYPE_PPTP:
1711 mtpd = new String[] {
1712 iface, "pptp", profile.server, "1723",
1713 "name", profile.username, "password", profile.password,
1714 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1715 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1716 (profile.mppe ? "+mppe" : "nomppe"),
1717 };
1718 break;
1719 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1720 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1721 mtpd = new String[] {
1722 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1723 "name", profile.username, "password", profile.password,
1724 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1725 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1726 };
1727 break;
1728 }
1729
1730 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001731 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001732 config.user = profile.key;
1733 config.interfaze = iface;
1734 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001735
1736 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001737 if (!profile.dnsServers.isEmpty()) {
1738 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1739 }
1740 if (!profile.searchDomains.isEmpty()) {
1741 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1742 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001743 startLegacyVpn(config, racoon, mtpd);
1744 }
1745
1746 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001747 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001748
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001749 // Prepare for the new request.
1750 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001751 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001752
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001753 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001754 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1755 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001756 }
1757
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001758 /** Stop legacy VPN. Permissions must be checked by callers. */
1759 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001760 if (mLegacyVpnRunner != null) {
1761 mLegacyVpnRunner.exit();
1762 mLegacyVpnRunner = null;
1763
1764 synchronized (LegacyVpnRunner.TAG) {
1765 // wait for old thread to completely finish before spinning up
1766 // new instance, otherwise state updates can be out of order.
1767 }
1768 }
1769 }
1770
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001771 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001772 * Return the information of the current ongoing legacy VPN.
1773 */
1774 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001775 // Check if the caller is authorized.
1776 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001777 return getLegacyVpnInfoPrivileged();
1778 }
1779
1780 /**
1781 * Return the information of the current ongoing legacy VPN.
1782 * Callers are responsible for checking permissions if needed.
1783 */
1784 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001785 if (mLegacyVpnRunner == null) return null;
1786
1787 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001788 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001789 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001790 if (mNetworkInfo.isConnected()) {
1791 info.intent = mStatusIntent;
1792 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001793 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001794 }
1795
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001796 public VpnConfig getLegacyVpnConfig() {
1797 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001798 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001799 } else {
1800 return null;
1801 }
1802 }
1803
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001804 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001805 * Bringing up a VPN connection takes time, and that is all this thread
1806 * does. Here we have plenty of time. The only thing we need to take
1807 * care of is responding to interruptions as soon as possible. Otherwise
Chalard Jeandd59ece2017-12-20 13:23:32 +09001808 * requests will pile up. This could be done in a Handler as a state
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001809 * machine, but it is much easier to read in the current form.
1810 */
1811 private class LegacyVpnRunner extends Thread {
1812 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001813
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001814 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001815 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001816 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001817 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001818 private final AtomicInteger mOuterConnection =
1819 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001820
Chalard Jeandd59ece2017-12-20 13:23:32 +09001821 private long mBringupStartTime = -1;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001822
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001823 /**
1824 * Watch for the outer connection (passing in the constructor) going away.
1825 */
1826 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1827 @Override
1828 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001829 if (!mEnableTeardown) return;
1830
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001831 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1832 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1833 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1834 NetworkInfo info = (NetworkInfo)intent.getExtra(
1835 ConnectivityManager.EXTRA_NETWORK_INFO);
1836 if (info != null && !info.isConnectedOrConnecting()) {
1837 try {
1838 mObserver.interfaceStatusChanged(mOuterInterface, false);
1839 } catch (RemoteException e) {}
1840 }
1841 }
1842 }
1843 }
1844 };
1845
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001846 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001847 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001848 mConfig = config;
1849 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001850 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001851 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001852 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001853
1854 // This is the interface which VPN is running on,
1855 // mConfig.interfaze will change to point to OUR
1856 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001857 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001858 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001859 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001860 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001861
Paul Jensene75b9e32015-04-06 11:54:53 -04001862 if (!TextUtils.isEmpty(mOuterInterface)) {
1863 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1864 for (Network network : cm.getAllNetworks()) {
1865 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001866 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001867 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1868 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1869 }
1870 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001871 }
1872
1873 IntentFilter filter = new IntentFilter();
1874 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1875 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001876 }
1877
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001878 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001879 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001880 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1881 exit();
1882 }
1883 }
1884
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001885 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001886 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001887 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001888 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001889 try {
1890 mContext.unregisterReceiver(mBroadcastReceiver);
1891 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001892 }
1893
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001894 @Override
1895 public void run() {
1896 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001897 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001898 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001899 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001900 try {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001901 bringup();
1902 waitForDaemonsToStop();
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001903 interrupted(); // Clear interrupt flag if execute called exit.
1904 } catch (InterruptedException e) {
1905 } finally {
1906 for (LocalSocket socket : mSockets) {
1907 IoUtils.closeQuietly(socket);
1908 }
1909 // This sleep is necessary for racoon to successfully complete sending delete
1910 // message to server.
1911 try {
1912 Thread.sleep(50);
1913 } catch (InterruptedException e) {
1914 }
1915 for (String daemon : mDaemons) {
1916 SystemService.stop(daemon);
1917 }
1918 }
1919 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001920 }
1921 }
1922
Chalard Jeandd59ece2017-12-20 13:23:32 +09001923 private void checkInterruptAndDelay(boolean sleepLonger) throws InterruptedException {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001924 long now = SystemClock.elapsedRealtime();
Chalard Jeandd59ece2017-12-20 13:23:32 +09001925 if (now - mBringupStartTime <= 60000) {
1926 Thread.sleep(sleepLonger ? 200 : 1);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001927 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001928 updateState(DetailedState.FAILED, "checkpoint");
Chalard Jeandd59ece2017-12-20 13:23:32 +09001929 throw new IllegalStateException("VPN bringup took too long");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001930 }
1931 }
1932
Chalard Jeandd59ece2017-12-20 13:23:32 +09001933 private void bringup() {
1934 // Catch all exceptions so we can clean up a few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001935 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001936 try {
1937 // Initialize the timer.
Chalard Jeandd59ece2017-12-20 13:23:32 +09001938 mBringupStartTime = SystemClock.elapsedRealtime();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001939
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001940 // Wait for the daemons to stop.
1941 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001942 while (!SystemService.isStopped(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001943 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001944 }
1945 }
1946
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001947 // Clear the previous state.
1948 File state = new File("/data/misc/vpn/state");
1949 state.delete();
1950 if (state.exists()) {
1951 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001952 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001953 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001954 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001955
Chia-chi Yehe9107902011-07-02 01:48:50 -07001956 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001957 boolean restart = false;
1958 for (String[] arguments : mArguments) {
1959 restart = restart || (arguments != null);
1960 }
1961 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001962 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001963 return;
1964 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001965 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001966
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001967 // Start the daemon with arguments.
1968 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001969 String[] arguments = mArguments[i];
1970 if (arguments == null) {
1971 continue;
1972 }
1973
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001974 // Start the daemon.
1975 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001976 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001977
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001978 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001979 while (!SystemService.isRunning(daemon)) {
Chalard Jeandd59ece2017-12-20 13:23:32 +09001980 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001981 }
1982
1983 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001984 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001985 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001986 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001987
1988 // Wait for the socket to connect.
1989 while (true) {
1990 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001991 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001992 break;
1993 } catch (Exception e) {
1994 // ignore
1995 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09001996 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001997 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001998 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001999
2000 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002001 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002002 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07002003 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002004 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002005 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002006 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002007 out.write(bytes.length >> 8);
2008 out.write(bytes.length);
2009 out.write(bytes);
Chalard Jeandd59ece2017-12-20 13:23:32 +09002010 checkInterruptAndDelay(false);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002011 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002012 out.write(0xFF);
2013 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002014 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002015
2016 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07002017 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002018 while (true) {
2019 try {
2020 if (in.read() == -1) {
2021 break;
2022 }
2023 } catch (Exception e) {
2024 // ignore
2025 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002026 checkInterruptAndDelay(true);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002027 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002028 }
2029
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002030 // Wait for the daemons to create the new state.
2031 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07002032 // Check if a running daemon is dead.
2033 for (int i = 0; i < mDaemons.length; ++i) {
2034 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07002035 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002036 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002037 }
2038 }
Chalard Jeandd59ece2017-12-20 13:23:32 +09002039 checkInterruptAndDelay(true);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002040 }
2041
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002042 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08002043 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09002044 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002045 throw new IllegalStateException("Cannot parse the state");
2046 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002047
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002048 // Set the interface and the addresses in the config.
2049 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002050
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002051 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002052 // Set the routes if they are not set in the config.
2053 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002054 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002055 }
2056
2057 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002058 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002059 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002060 if (!dnsServers.isEmpty()) {
2061 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
2062 }
2063 }
2064
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002065 // Set the search domains if they are not set in the config.
2066 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
2067 String searchDomains = parameters[4].trim();
2068 if (!searchDomains.isEmpty()) {
2069 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
2070 }
2071 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002072
Lorenzo Colitti50262792014-09-19 01:53:35 +09002073 // Add a throw route for the VPN server endpoint, if one was specified.
2074 String endpoint = parameters[5];
2075 if (!endpoint.isEmpty()) {
2076 try {
2077 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
2078 if (addr instanceof Inet4Address) {
2079 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
2080 } else if (addr instanceof Inet6Address) {
2081 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
2082 } else {
2083 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
2084 }
2085 } catch (IllegalArgumentException e) {
2086 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
2087 }
2088 }
2089
Chia-chi Yeh97a61562011-07-14 15:05:05 -07002090 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002091 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07002092 // Set the start time
2093 mConfig.startTime = SystemClock.elapsedRealtime();
2094
Chalard Jeandd59ece2017-12-20 13:23:32 +09002095 // Check if the thread was interrupted while we were waiting on the lock.
2096 checkInterruptAndDelay(false);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002097
Chia-chi Yehe9107902011-07-02 01:48:50 -07002098 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002099 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07002100 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002101 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07002102
2103 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07002104 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01002105 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002106
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002107 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002108
2109 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07002110 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002111 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002112 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07002113 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07002114 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002115 }
2116 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002117
2118 /**
Chalard Jeandd59ece2017-12-20 13:23:32 +09002119 * Check all daemons every two seconds. Return when one of them is stopped.
2120 * The caller will move to the disconnected state when this function returns,
2121 * which can happen if a daemon failed or if the VPN was torn down.
Jeff Sharkey899223b2012-08-04 15:24:58 -07002122 */
Chalard Jeandd59ece2017-12-20 13:23:32 +09002123 private void waitForDaemonsToStop() throws InterruptedException {
Jeff Sharkey899223b2012-08-04 15:24:58 -07002124 if (!mNetworkInfo.isConnected()) {
2125 return;
2126 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09002127 while (true) {
2128 Thread.sleep(2000);
2129 for (int i = 0; i < mDaemons.length; i++) {
2130 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
2131 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07002132 }
2133 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07002134 }
2135 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07002136 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002137}