blob: 9fc2fc7bb31ef068e7e77faeef570a83e1ad2aad [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;
Lorenzo Colitti50262792014-09-19 01:53:35 +090021import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090022import static android.net.RouteInfo.RTN_UNREACHABLE;
Jeff Sharkey899223b2012-08-04 15:24:58 -070023
Jeff Davidsonbc19c182014-11-11 13:20:01 -080024import android.Manifest;
Robin Lee4d03abc2016-05-09 12:32:27 +010025import android.annotation.NonNull;
26import android.annotation.Nullable;
27import android.annotation.UserIdInt;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070028import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070029import android.app.AppOpsManager;
Tony Mak1a405fe2016-06-30 11:19:20 +010030import android.app.Notification;
31import android.app.NotificationManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070032import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070033import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.ComponentName;
Robin Lee812800c2016-05-13 15:38:08 +010035import android.content.ContentResolver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.content.Context;
37import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070038import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070039import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070040import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040041import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070042import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070043import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070044import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070045import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090046import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070047import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070048import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070049import android.net.LocalSocket;
50import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080051import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040052import android.net.NetworkAgent;
53import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070054import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040055import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070056import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070057import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.net.UidRange;
Robin Lee812800c2016-05-13 15:38:08 +010059import android.net.Uri;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070060import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080061import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070062import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070063import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040064import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070065import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070066import android.os.ParcelFileDescriptor;
Robin Lee812800c2016-05-13 15:38:08 +010067import android.os.PatternMatcher;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070068import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070069import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070070import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070071import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070072import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070073import android.os.UserManager;
Robin Lee812800c2016-05-13 15:38:08 +010074import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070075import android.security.Credentials;
76import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040077import android.text.TextUtils;
Robin Lee4d03abc2016-05-09 12:32:27 +010078import android.util.ArraySet;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070079import android.util.Log;
80
Tony Mak1a405fe2016-06-30 11:19:20 +010081import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070082import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010083import com.android.internal.annotations.VisibleForTesting;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070084import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070085import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080086import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050088import com.android.internal.notification.SystemNotificationChannels;
Christopher Tatee0be7e82017-02-08 17:38:20 -080089import com.android.server.DeviceIdleController;
90import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -070091import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092
Jeff Davidson05542602014-08-11 14:07:27 -070093import libcore.io.IoUtils;
94
Chia-chi Yeh97a61562011-07-14 15:05:05 -070095import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070096import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070097import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070098import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070099import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700100import java.net.Inet6Address;
101import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700102import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700104import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100105import java.util.Collection;
106import java.util.Collections;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +0100108import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400109import java.util.SortedSet;
110import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700111import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700112
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700113/**
114 * @hide
115 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400116public class Vpn {
117 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700118 private static final String TAG = "Vpn";
119 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120
Christopher Tatee0be7e82017-02-08 17:38:20 -0800121 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
122 // the device idle whitelist during service launch and VPN bootstrap.
123 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION = 60 * 1000;
124
Jeff Sharkey899223b2012-08-04 15:24:58 -0700125 // TODO: create separate trackers for each unique VPN to support
126 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 private Context mContext;
129 private NetworkInfo mNetworkInfo;
130 private String mPackage;
131 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700132 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700133 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700134 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700135 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700136 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700138 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400139 private NetworkAgent mNetworkAgent;
140 private final Looper mLooper;
141 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700142
Robin Lee4d03abc2016-05-09 12:32:27 +0100143 /**
Robin Lee17e61832016-05-09 13:46:28 +0100144 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
145 * only applies to {@link VpnService} connections.
146 */
147 private boolean mAlwaysOn = false;
148
149 /**
150 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
151 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
152 * not set.
153 */
154 private boolean mLockdown = false;
155
156 /**
Robin Lee4d03abc2016-05-09 12:32:27 +0100157 * List of UIDs that are set to use this VPN by default. Normally, every UID in the user is
158 * added to this set but that can be changed by adding allowed or disallowed applications. It
159 * is non-null iff the VPN is connected.
160 *
161 * Unless the VPN has set allowBypass=true, these UIDs are forced into the VPN.
162 *
163 * @see VpnService.Builder#addAllowedApplication(String)
164 * @see VpnService.Builder#addDisallowedApplication(String)
165 */
Chad Brubakerc2865192013-07-10 14:46:23 -0700166 @GuardedBy("this")
Robin Lee4d03abc2016-05-09 12:32:27 +0100167 private Set<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700168
Robin Lee17e61832016-05-09 13:46:28 +0100169 /**
170 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
171 * when VPN is not running. For example, during system startup or after a crash.
172 * @see mLockdown
173 */
174 @GuardedBy("this")
175 private Set<UidRange> mBlockedUsers = new ArraySet<>();
176
Paul Jensen0784eea2014-08-19 16:00:24 -0400177 // Handle of user initiating VPN.
178 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700179
Robin Lee812800c2016-05-13 15:38:08 +0100180 // Listen to package remove and change event in this user
181 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
182 @Override
183 public void onReceive(Context context, Intent intent) {
184 final Uri data = intent.getData();
185 final String packageName = data == null ? null : data.getSchemeSpecificPart();
186 if (packageName == null) {
187 return;
188 }
189
190 synchronized (Vpn.this) {
191 // Avoid race that always-on package has been unset
192 if (!packageName.equals(getAlwaysOnPackage())) {
193 return;
194 }
195
196 final String action = intent.getAction();
197 Log.i(TAG, "Received broadcast " + action + " for always-on package " + packageName
198 + " in user " + mUserHandle);
199
200 switch(action) {
201 case Intent.ACTION_PACKAGE_REPLACED:
202 // Start vpn after app upgrade
203 startAlwaysOnVpn();
204 break;
205 case Intent.ACTION_PACKAGE_REMOVED:
206 final boolean isPackageRemoved = !intent.getBooleanExtra(
207 Intent.EXTRA_REPLACING, false);
208 if (isPackageRemoved) {
209 setAndSaveAlwaysOnPackage(null, false);
210 }
211 break;
212 }
213 }
214 }
215 };
216
217 private boolean mIsPackageIntentReceiverRegistered = false;
218
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400219 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400220 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700221 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400222 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400223 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400224 mLooper = looper;
225
226 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400227 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700228
229 try {
230 netService.registerObserver(mObserver);
231 } catch (RemoteException e) {
232 Log.wtf(TAG, "Problem registering observer", e);
233 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400234
235 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
236 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
237 mNetworkCapabilities = new NetworkCapabilities();
238 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
239 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700240 }
241
Jeff Sharkey57666932013-04-30 17:01:57 -0700242 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700243 * Set if this object is responsible for watching for {@link NetworkInfo}
244 * teardown. When {@code false}, teardown is handled externally by someone
245 * else.
246 */
247 public void setEnableTeardown(boolean enableTeardown) {
248 mEnableTeardown = enableTeardown;
249 }
250
Jeff Sharkey899223b2012-08-04 15:24:58 -0700251 /**
252 * Update current state, dispaching event to listeners.
253 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100254 @VisibleForTesting
255 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700256 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
257 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400258 if (mNetworkAgent != null) {
259 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
260 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100261 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700262 }
263
264 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000265 * Configures an always-on VPN connection through a specific application.
266 * This connection is automatically granted and persisted after a reboot.
267 *
268 * <p>The designated package should exist and declare a {@link VpnService} in its
269 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
270 * otherwise the call will fail.
271 *
Robin Lee17e61832016-05-09 13:46:28 +0100272 * @param packageName the package to designate as always-on VPN supplier.
273 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100274 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000275 */
Robin Lee17e61832016-05-09 13:46:28 +0100276 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000277 enforceControlPermissionOrInternalCaller();
Robin Lee9ff1a582016-06-10 16:41:10 +0100278 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
279 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
280 return false;
281 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000282
Robin Lee244ce8e2016-01-05 18:03:46 +0000283 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100284 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000285 if (!setPackageAuthorization(packageName, true)) {
286 return false;
287 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100288 mAlwaysOn = true;
289 } else {
290 packageName = VpnConfig.LEGACY_VPN;
291 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000292 }
293
Robin Lee17e61832016-05-09 13:46:28 +0100294 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100295 if (isCurrentPreparedPackage(packageName)) {
296 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
297 } else {
298 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100299 prepareInternal(packageName);
300 }
Robin Lee812800c2016-05-13 15:38:08 +0100301 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100302 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000303 return true;
304 }
305
Robin Lee9ff1a582016-06-10 16:41:10 +0100306 private static boolean isNullOrLegacyVpn(String packageName) {
307 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
308 }
309
Robin Lee812800c2016-05-13 15:38:08 +0100310 private void unregisterPackageChangeReceiverLocked() {
311 // register previous intent filter
312 if (mIsPackageIntentReceiverRegistered) {
313 mContext.unregisterReceiver(mPackageIntentReceiver);
314 mIsPackageIntentReceiverRegistered = false;
315 }
316 }
317
318 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
319 // Unregister IntentFilter listening for previous always-on package change
320 unregisterPackageChangeReceiverLocked();
321
Robin Lee9ff1a582016-06-10 16:41:10 +0100322 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100323 mIsPackageIntentReceiverRegistered = true;
324
325 IntentFilter intentFilter = new IntentFilter();
326 // Protected intent can only be sent by system. No permission required in register.
327 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
328 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
329 intentFilter.addDataScheme("package");
330 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
331 mContext.registerReceiverAsUser(
332 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
333 }
334 }
335
Robin Lee244ce8e2016-01-05 18:03:46 +0000336 /**
337 * @return the package name of the VPN controller responsible for always-on VPN,
338 * or {@code null} if none is set or always-on VPN is controlled through
339 * lockdown instead.
340 * @hide
341 */
342 public synchronized String getAlwaysOnPackage() {
343 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100344 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000345 }
346
347 /**
Robin Lee812800c2016-05-13 15:38:08 +0100348 * Save the always-on package and lockdown config into Settings.Secure
349 */
350 public synchronized void saveAlwaysOnPackage() {
351 final long token = Binder.clearCallingIdentity();
352 try {
353 final ContentResolver cr = mContext.getContentResolver();
354 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
355 getAlwaysOnPackage(), mUserHandle);
356 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
357 (mLockdown ? 1 : 0), mUserHandle);
358 } finally {
359 Binder.restoreCallingIdentity(token);
360 }
361 }
362
363 /**
364 * Set and save always-on package and lockdown config
365 * @see Vpn#setAlwaysOnPackage(String, boolean)
366 * @see Vpn#saveAlwaysOnPackage()
367 *
368 * @return result of Vpn#setAndSaveAlwaysOnPackage(String, boolean)
369 */
370 private synchronized boolean setAndSaveAlwaysOnPackage(String packageName, boolean lockdown) {
371 if (setAlwaysOnPackage(packageName, lockdown)) {
372 saveAlwaysOnPackage();
373 return true;
374 } else {
375 return false;
376 }
377 }
378
379 /**
380 * @return {@code true} if the service was started, the service was already connected, or there
381 * was no always-on VPN to start. {@code false} otherwise.
382 */
383 public boolean startAlwaysOnVpn() {
384 final String alwaysOnPackage;
385 synchronized (this) {
386 alwaysOnPackage = getAlwaysOnPackage();
387 // Skip if there is no service to start.
388 if (alwaysOnPackage == null) {
389 return true;
390 }
391 // Skip if the service is already established. This isn't bulletproof: it's not bound
392 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
393 // which may restart the connection.
394 if (getNetworkInfo().isConnected()) {
395 return true;
396 }
397 }
398
Christopher Tatee0be7e82017-02-08 17:38:20 -0800399 // Tell the OS that background services in this app need to be allowed for
400 // a short time, so we can bootstrap the VPN service.
401 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100402 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800403 DeviceIdleController.LocalService idleController =
404 LocalServices.getService(DeviceIdleController.LocalService.class);
405 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
406 VPN_LAUNCH_IDLE_WHITELIST_DURATION, mUserHandle, false, "vpn");
407
408 // Start the VPN service declared in the app's manifest.
409 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
410 serviceIntent.setPackage(alwaysOnPackage);
411 try {
412 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
413 } catch (RuntimeException e) {
414 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
415 return false;
416 }
417 } finally {
418 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100419 }
420 }
421
422 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700423 * Prepare for a VPN application. This method is designed to solve
424 * race conditions. It first compares the current prepared package
425 * with {@code oldPackage}. If they are the same, the prepared
426 * package is revoked and replaced with {@code newPackage}. If
427 * {@code oldPackage} is {@code null}, the comparison is omitted.
428 * If {@code newPackage} is the same package or {@code null}, the
429 * revocation is omitted. This method returns {@code true} if the
430 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700431 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700432 * Legacy VPN is handled specially since it is not a real package.
433 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
434 * it can be revoked by itself.
435 *
Victor Chang98a633a2016-05-27 17:30:49 +0100436 * Note: when we added VPN pre-consent in http://ag/522961 the names oldPackage
437 * and newPackage become misleading, because when an app is pre-consented, we
438 * actually prepare oldPackage, not newPackage.
439 *
440 * Their meanings actually are:
441 *
442 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
443 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100444 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100445 * and revoke any current app VPN and re-prepare legacy vpn.
446 *
Robin Lee812800c2016-05-13 15:38:08 +0100447 * TODO: Rename the variables - or split this method into two - and end this confusion.
448 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
449 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100450 *
451 * @param oldPackage The package name of the old VPN application
452 * @param newPackage The package name of the new VPN application
453 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700454 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700455 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700456 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700457 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100458 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100459 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100460 return false;
461 }
462
463 // Package is not same or old package was reinstalled.
464 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700465 // The package doesn't match. We return false (to obtain user consent) unless the
466 // user has already consented to that VPN package.
467 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
468 prepareInternal(oldPackage);
469 return true;
470 }
471 return false;
472 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
473 && !isVpnUserPreConsented(oldPackage)) {
474 // Currently prepared VPN is revoked, so unprepare it and return false.
475 prepareInternal(VpnConfig.LEGACY_VPN);
476 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700477 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700478 }
479
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700480 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700481 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100482 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700483 return true;
484 }
485
Robin Lee1b1bcd72016-02-12 18:11:30 +0000486 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700487 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700488
Victor Chang98a633a2016-05-27 17:30:49 +0100489 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100490 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100491 return false;
492 }
493
Jeff Davidson11008a72014-11-20 13:12:46 -0800494 prepareInternal(newPackage);
495 return true;
496 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700497
Victor Chang98a633a2016-05-27 17:30:49 +0100498 private boolean isCurrentPreparedPackage(String packageName) {
499 // We can't just check that packageName matches mPackage, because if the app was uninstalled
500 // and reinstalled it will no longer be prepared. Instead check the UID.
501 return getAppUid(packageName, mUserHandle) == mOwnerUID;
502 }
503
Jeff Davidson11008a72014-11-20 13:12:46 -0800504 /** Prepare the VPN for the given package. Does not perform permission checks. */
505 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400506 long token = Binder.clearCallingIdentity();
507 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800508 // Reset the interface.
509 if (mInterface != null) {
510 mStatusIntent = null;
511 agentDisconnect();
512 jniReset(mInterface);
513 mInterface = null;
514 mVpnUsers = null;
515 }
516
517 // Revoke the connection or stop LegacyVpnRunner.
518 if (mConnection != null) {
519 try {
520 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
521 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
522 } catch (Exception e) {
523 // ignore
524 }
525 mContext.unbindService(mConnection);
526 mConnection = null;
527 } else if (mLegacyVpnRunner != null) {
528 mLegacyVpnRunner.exit();
529 mLegacyVpnRunner = null;
530 }
531
532 try {
533 mNetd.denyProtect(mOwnerUID);
534 } catch (Exception e) {
535 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
536 }
537
538 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
539 mPackage = newPackage;
540 mOwnerUID = getAppUid(newPackage, mUserHandle);
541 try {
542 mNetd.allowProtect(mOwnerUID);
543 } catch (Exception e) {
544 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
545 }
546 mConfig = null;
547
548 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400549 } finally {
550 Binder.restoreCallingIdentity(token);
551 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700552 }
553
Jeff Davidson05542602014-08-11 14:07:27 -0700554 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100555 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700556 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000557 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700558 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000559 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700560
Robin Lee3b3dd942015-05-12 18:14:58 +0100561 int uid = getAppUid(packageName, mUserHandle);
562 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
563 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000564 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700565 }
566
567 long token = Binder.clearCallingIdentity();
568 try {
569 AppOpsManager appOps =
570 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100571 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700572 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000573 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700574 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100575 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700576 } finally {
577 Binder.restoreCallingIdentity(token);
578 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000579 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700580 }
581
582 private boolean isVpnUserPreConsented(String packageName) {
583 AppOpsManager appOps =
584 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
585
586 // Verify that the caller matches the given package and has permission to activate VPNs.
587 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
588 packageName) == AppOpsManager.MODE_ALLOWED;
589 }
590
Paul Jensen0784eea2014-08-19 16:00:24 -0400591 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700592 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400593 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700594 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400595 PackageManager pm = mContext.getPackageManager();
596 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700597 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700598 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400599 } catch (NameNotFoundException e) {
600 result = -1;
601 }
602 return result;
603 }
604
605 public NetworkInfo getNetworkInfo() {
606 return mNetworkInfo;
607 }
608
Paul Jensen31a94f42015-02-13 14:18:39 -0500609 public int getNetId() {
610 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
611 }
612
Lorenzo Colitti60446162014-09-20 00:14:31 +0900613 private LinkProperties makeLinkProperties() {
614 boolean allowIPv4 = mConfig.allowIPv4;
615 boolean allowIPv6 = mConfig.allowIPv6;
616
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400617 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900618
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400619 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700620
Lorenzo Colitti60446162014-09-20 00:14:31 +0900621 if (mConfig.addresses != null) {
622 for (LinkAddress address : mConfig.addresses) {
623 lp.addLinkAddress(address);
624 allowIPv4 |= address.getAddress() instanceof Inet4Address;
625 allowIPv6 |= address.getAddress() instanceof Inet6Address;
626 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400627 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900628
629 if (mConfig.routes != null) {
630 for (RouteInfo route : mConfig.routes) {
631 lp.addRoute(route);
632 InetAddress address = route.getDestination().getAddress();
633 allowIPv4 |= address instanceof Inet4Address;
634 allowIPv6 |= address instanceof Inet6Address;
635 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400636 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700637
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400638 if (mConfig.dnsServers != null) {
639 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700640 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
641 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900642 allowIPv4 |= address instanceof Inet4Address;
643 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400644 }
645 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700646
Lorenzo Colitti60446162014-09-20 00:14:31 +0900647 if (!allowIPv4) {
648 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
649 }
650 if (!allowIPv6) {
651 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
652 }
653
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400654 // Concatenate search domains into a string.
655 StringBuilder buffer = new StringBuilder();
656 if (mConfig.searchDomains != null) {
657 for (String domain : mConfig.searchDomains) {
658 buffer.append(domain).append(' ');
659 }
660 }
661 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700662
Lorenzo Colitti60446162014-09-20 00:14:31 +0900663 // TODO: Stop setting the MTU in jniCreate and set it here.
664
665 return lp;
666 }
667
668 private void agentConnect() {
669 LinkProperties lp = makeLinkProperties();
670
671 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
672 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
673 } else {
674 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
675 }
676
Robin Lee323f29d2016-05-04 16:38:06 +0100677 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700678
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700679 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100680 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700681
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400682 long token = Binder.clearCallingIdentity();
683 try {
684 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700685 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700686 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400687 public void unwanted() {
688 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700689 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400690 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700691 } finally {
692 Binder.restoreCallingIdentity(token);
693 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700694
Robin Lee4d03abc2016-05-09 12:32:27 +0100695 mVpnUsers = createUserAndRestrictedProfilesRanges(mUserHandle,
696 mConfig.allowedApplications, mConfig.disallowedApplications);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400697 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
Robin Lee323f29d2016-05-04 16:38:06 +0100698
699 mNetworkInfo.setIsAvailable(true);
700 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400701 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700702
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700703 private boolean canHaveRestrictedProfile(int userId) {
704 long token = Binder.clearCallingIdentity();
705 try {
706 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
707 } finally {
708 Binder.restoreCallingIdentity(token);
709 }
710 }
711
Tony Mak1a405fe2016-06-30 11:19:20 +0100712 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400713 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100714 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
715 networkInfo.setIsAvailable(false);
716 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400717 networkAgent.sendNetworkInfo(networkInfo);
718 }
719 }
720
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400721 private void agentDisconnect() {
722 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100723 mNetworkInfo.setIsAvailable(false);
724 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400725 mNetworkAgent = null;
726 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700727 }
728
729 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700730 * Establish a VPN network and return the file descriptor of the VPN
731 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700732 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700733 *
734 * @param config The parameters to configure the network.
735 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700736 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700737 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700738 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700739 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400740 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700741 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700742 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700743 // Check to ensure consent hasn't been revoked since we were prepared.
744 if (!isVpnUserPreConsented(mPackage)) {
745 return null;
746 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700747 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700748 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
749 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700750 long token = Binder.clearCallingIdentity();
751 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700752 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400753 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100754 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700755 throw new SecurityException("Restricted users cannot establish VPNs");
756 }
757
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700758 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400759 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700760 if (info == null) {
761 throw new SecurityException("Cannot find " + config.user);
762 }
763 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
764 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
765 }
766 } catch (RemoteException e) {
767 throw new SecurityException("Cannot find " + config.user);
768 } finally {
769 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700770 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700771
Chad Brubaker850eb672014-03-21 21:02:47 +0000772 // Save the old config in case we need to go back.
773 VpnConfig oldConfig = mConfig;
774 String oldInterface = mInterface;
775 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400776 NetworkAgent oldNetworkAgent = mNetworkAgent;
777 mNetworkAgent = null;
Robin Lee4d03abc2016-05-09 12:32:27 +0100778 Set<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000779
Chia-chi Yehe9107902011-07-02 01:48:50 -0700780 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700781 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700782 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700783 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700784 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700785
Chad Brubakerc2865192013-07-10 14:46:23 -0700786 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700787 StringBuilder builder = new StringBuilder();
788 for (LinkAddress address : config.addresses) {
789 builder.append(" " + address);
790 }
791 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700792 throw new IllegalArgumentException("At least one address must be specified");
793 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700794 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700795 if (!mContext.bindServiceAsUser(intent, connection,
796 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
797 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700798 throw new IllegalStateException("Cannot bind " + config.user);
799 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000800
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700801 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700802 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700803
804 // Fill more values.
805 config.user = mPackage;
806 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700807 config.startTime = SystemClock.elapsedRealtime();
808 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000809
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700810 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400811 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000812
813 if (oldConnection != null) {
814 mContext.unbindService(oldConnection);
815 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400816 // Remove the old tun's user forwarding rules
817 // The new tun's user rules have already been added so they will take over
818 // as rules are deleted. This prevents data leakage as the rules are moved over.
819 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000820 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000821 jniReset(oldInterface);
822 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700823
824 try {
825 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
826 } catch (IOException e) {
827 throw new IllegalStateException(
828 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
829 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000830 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000831 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400832 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000833 // restore old state
834 mConfig = oldConfig;
835 mConnection = oldConnection;
836 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400837 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000838 mInterface = oldInterface;
839 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700840 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000841 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700842 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700843 }
844
Chad Brubakerc2865192013-07-10 14:46:23 -0700845 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800846 return mNetworkAgent != null && mInterface != null;
847 }
848
849 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
850 // that a call to mutate VPN state is admissible.
851 private boolean isCallerEstablishedOwnerLocked() {
852 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700853 }
854
Paul Jensen0784eea2014-08-19 16:00:24 -0400855 // Note: Return type guarantees results are deduped and sorted, which callers require.
856 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
857 SortedSet<Integer> uids = new TreeSet<Integer>();
858 for (String app : packageNames) {
859 int uid = getAppUid(app, userHandle);
860 if (uid != -1) uids.add(uid);
861 }
862 return uids;
863 }
864
Robin Lee4d03abc2016-05-09 12:32:27 +0100865 /**
866 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
867 * associated with one user, and any restricted profiles attached to that user.
868 *
869 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
870 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
871 * in each user and profile will be included.
872 *
873 * @param userHandle The userId to create UID ranges for along with any of its restricted
874 * profiles.
875 * @param allowedApplications (optional) whitelist of applications to include.
876 * @param disallowedApplications (optional) blacklist of applications to exclude.
877 */
878 @VisibleForTesting
879 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
880 @Nullable List<String> allowedApplications,
881 @Nullable List<String> disallowedApplications) {
882 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700883
Robin Lee4d03abc2016-05-09 12:32:27 +0100884 // Assign the top-level user to the set of ranges
885 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
886
887 // If the user can have restricted profiles, assign all its restricted profiles too
888 if (canHaveRestrictedProfile(userHandle)) {
889 final long token = Binder.clearCallingIdentity();
890 List<UserInfo> users;
891 try {
Robin Lee17e61832016-05-09 13:46:28 +0100892 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +0100893 } finally {
894 Binder.restoreCallingIdentity(token);
895 }
896 for (UserInfo user : users) {
897 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
898 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
899 }
900 }
901 }
902 return ranges;
903 }
904
905 /**
906 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
907 * associated with one user.
908 *
909 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
910 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
911 * in the user will be included.
912 *
913 * @param ranges {@link Set} of {@link UidRange}s to which to add.
914 * @param userHandle The userId to add to {@param ranges}.
915 * @param allowedApplications (optional) whitelist of applications to include.
916 * @param disallowedApplications (optional) blacklist of applications to exclude.
917 */
918 @VisibleForTesting
919 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
920 @Nullable List<String> allowedApplications,
921 @Nullable List<String> disallowedApplications) {
922 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400923 // Add ranges covering all UIDs for allowedApplications.
924 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +0100925 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400926 if (start == -1) {
927 start = uid;
928 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100929 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400930 start = uid;
931 }
932 stop = uid;
933 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100934 if (start != -1) ranges.add(new UidRange(start, stop));
935 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400936 // Add all ranges for user skipping UIDs for disallowedApplications.
937 final UidRange userRange = UidRange.createForUser(userHandle);
938 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +0100939 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400940 if (uid == start) {
941 start++;
942 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +0100943 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -0400944 start = uid + 1;
945 }
946 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100947 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400948 } else {
949 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +0100950 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -0400951 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700952 }
953
Paul Jensen0784eea2014-08-19 16:00:24 -0400954 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
955 // apply to userHandle.
956 private List<UidRange> uidRangesForUser(int userHandle) {
957 final UidRange userRange = UidRange.createForUser(userHandle);
958 final List<UidRange> ranges = new ArrayList<UidRange>();
959 for (UidRange range : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100960 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400961 ranges.add(range);
962 }
963 }
964 return ranges;
965 }
966
967 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800968 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700969 throw new IllegalStateException("VPN is not active");
970 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400971 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700972 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400973 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700974 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400975 mVpnUsers.removeAll(ranges);
Chad Brubakerc2865192013-07-10 14:46:23 -0700976 }
977
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700978 public void onUserAdded(int userHandle) {
979 // If the user is restricted tie them to the parent user's VPN
980 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100981 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700982 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100983 if (mVpnUsers != null) {
984 try {
985 addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
986 mConfig.disallowedApplications);
987 if (mNetworkAgent != null) {
988 final List<UidRange> ranges = uidRangesForUser(userHandle);
989 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
990 }
991 } catch (Exception e) {
992 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400993 }
Robin Lee17e61832016-05-09 13:46:28 +0100994 }
995 if (mAlwaysOn) {
996 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700997 }
998 }
999 }
1000 }
1001
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001002 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001003 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001004 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001005 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001006 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +01001007 if (mVpnUsers != null) {
1008 try {
1009 removeVpnUserLocked(userHandle);
1010 } catch (Exception e) {
1011 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1012 }
1013 }
1014 if (mAlwaysOn) {
1015 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001016 }
1017 }
1018 }
1019 }
1020
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001021 /**
Robin Lee17e61832016-05-09 13:46:28 +01001022 * Called when the user associated with this VPN has just been stopped.
1023 */
1024 public synchronized void onUserStopped() {
1025 // Switch off networking lockdown (if it was enabled)
1026 setVpnForcedLocked(false);
1027 mAlwaysOn = false;
1028
Robin Lee812800c2016-05-13 15:38:08 +01001029 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001030 // Quit any active connections
1031 agentDisconnect();
1032 }
1033
1034 /**
1035 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1036 * service app itself, to only sockets that have had {@code protect()} called on them. All
1037 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1038 *
1039 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1040 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1041 *
1042 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1043 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1044 *
1045 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1046 * {@link Vpn} goes through a VPN connection or is blocked until one is
1047 * available, {@code false} to lift the requirement.
1048 *
1049 * @see #mBlockedUsers
1050 */
1051 @GuardedBy("this")
1052 private void setVpnForcedLocked(boolean enforce) {
1053 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
1054 if (enforce) {
1055 final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
1056 /* allowedApplications */ null,
1057 /* disallowedApplications */ Collections.singletonList(mPackage));
1058
1059 removedRanges.removeAll(addedRanges);
1060 addedRanges.removeAll(mBlockedUsers);
1061
1062 setAllowOnlyVpnForUids(false, removedRanges);
1063 setAllowOnlyVpnForUids(true, addedRanges);
1064 } else {
1065 setAllowOnlyVpnForUids(false, removedRanges);
1066 }
1067 }
1068
1069 /**
1070 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1071 * to make connections through sockets that have had {@code protect()} called on them.
1072 *
1073 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1074 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1075 * {@code true}) or to remove.
1076 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1077 * including added ranges that already existed or removed ones that didn't.
1078 */
1079 @GuardedBy("this")
1080 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1081 if (ranges.size() == 0) {
1082 return true;
1083 }
1084 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1085 try {
1086 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1087 } catch (RemoteException | RuntimeException e) {
1088 Log.e(TAG, "Updating blocked=" + enforce
1089 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1090 return false;
1091 }
1092 if (enforce) {
1093 mBlockedUsers.addAll(ranges);
1094 } else {
1095 mBlockedUsers.removeAll(ranges);
1096 }
1097 return true;
1098 }
1099
1100 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001101 * Return the configuration of the currently running VPN.
1102 */
1103 public VpnConfig getVpnConfig() {
1104 enforceControlPermission();
1105 return mConfig;
1106 }
1107
Jeff Sharkey899223b2012-08-04 15:24:58 -07001108 @Deprecated
1109 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1110 try {
1111 mObserver.interfaceStatusChanged(iface, up);
1112 } catch (RemoteException e) {
1113 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001114 }
1115 }
1116
Jeff Sharkey899223b2012-08-04 15:24:58 -07001117 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1118 @Override
1119 public void interfaceStatusChanged(String interfaze, boolean up) {
1120 synchronized (Vpn.this) {
1121 if (!up && mLegacyVpnRunner != null) {
1122 mLegacyVpnRunner.check(interfaze);
1123 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001124 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001125 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001126
Jeff Sharkey899223b2012-08-04 15:24:58 -07001127 @Override
1128 public void interfaceRemoved(String interfaze) {
1129 synchronized (Vpn.this) {
1130 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001131 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001132 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -05001133 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001134 mInterface = null;
1135 if (mConnection != null) {
1136 mContext.unbindService(mConnection);
1137 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001138 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001139 } else if (mLegacyVpnRunner != null) {
1140 mLegacyVpnRunner.exit();
1141 mLegacyVpnRunner = null;
1142 }
1143 }
1144 }
1145 }
1146 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001147
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001148 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001149 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001150 }
1151
Robin Lee244ce8e2016-01-05 18:03:46 +00001152 private void enforceControlPermissionOrInternalCaller() {
1153 // Require caller to be either an application with CONTROL_VPN permission or a process
1154 // in the system server.
1155 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1156 "Unauthorized Caller");
1157 }
1158
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001159 private class Connection implements ServiceConnection {
1160 private IBinder mService;
1161
1162 @Override
1163 public void onServiceConnected(ComponentName name, IBinder service) {
1164 mService = service;
1165 }
1166
1167 @Override
1168 public void onServiceDisconnected(ComponentName name) {
1169 mService = null;
1170 }
1171 }
1172
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001173 private void prepareStatusIntent() {
1174 final long token = Binder.clearCallingIdentity();
1175 try {
1176 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1177 } finally {
1178 Binder.restoreCallingIdentity(token);
1179 }
1180 }
1181
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001182 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001183 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001184 return false;
1185 }
1186 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001187 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001188 return success;
1189 }
1190
1191 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001192 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001193 return false;
1194 }
1195 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001196 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001197 return success;
1198 }
1199
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001200 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1201 if (!isCallerEstablishedOwnerLocked()) {
1202 return false;
1203 }
1204 if (networks == null) {
1205 mConfig.underlyingNetworks = null;
1206 } else {
1207 mConfig.underlyingNetworks = new Network[networks.length];
1208 for (int i = 0; i < networks.length; ++i) {
1209 if (networks[i] == null) {
1210 mConfig.underlyingNetworks[i] = null;
1211 } else {
1212 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1213 }
1214 }
1215 }
1216 return true;
1217 }
1218
1219 public synchronized Network[] getUnderlyingNetworks() {
1220 if (!isRunningLocked()) {
1221 return null;
1222 }
1223 return mConfig.underlyingNetworks;
1224 }
1225
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001226 /**
1227 * This method should only be called by ConnectivityService. Because it doesn't
1228 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1229 */
1230 public synchronized VpnInfo getVpnInfo() {
1231 if (!isRunningLocked()) {
1232 return null;
1233 }
1234
1235 VpnInfo info = new VpnInfo();
1236 info.ownerUid = mOwnerUID;
1237 info.vpnIface = mInterface;
1238 return info;
1239 }
1240
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001241 public synchronized boolean appliesToUid(int uid) {
1242 if (!isRunningLocked()) {
1243 return false;
1244 }
1245 for (UidRange uidRange : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001246 if (uidRange.contains(uid)) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001247 return true;
1248 }
1249 }
1250 return false;
1251 }
1252
Robin Lee17e61832016-05-09 13:46:28 +01001253 /**
Robin Leeebbcb542016-05-24 16:35:10 +01001254 * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1255 * A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1256 * not connected, or if the VPN is connected but does not apply to the UID.
Robin Lee17e61832016-05-09 13:46:28 +01001257 *
1258 * @see #mBlockedUsers
1259 */
1260 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001261 if (!mLockdown) {
1262 return false;
Robin Lee17e61832016-05-09 13:46:28 +01001263 }
Robin Leeebbcb542016-05-24 16:35:10 +01001264
1265 if (mNetworkInfo.isConnected()) {
1266 return !appliesToUid(uid);
1267 } else {
1268 for (UidRange uidRange : mBlockedUsers) {
1269 if (uidRange.contains(uid)) {
1270 return true;
1271 }
1272 }
1273 return false;
1274 }
Robin Lee17e61832016-05-09 13:46:28 +01001275 }
1276
Tony Mak1a405fe2016-06-30 11:19:20 +01001277 private void updateAlwaysOnNotification(DetailedState networkState) {
1278 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
1279 updateAlwaysOnNotificationInternal(visible);
1280 }
1281
1282 @VisibleForTesting
1283 protected void updateAlwaysOnNotificationInternal(boolean visible) {
1284 final UserHandle user = UserHandle.of(mUserHandle);
1285 final long token = Binder.clearCallingIdentity();
1286 try {
1287 final NotificationManager notificationManager = NotificationManager.from(mContext);
1288 if (!visible) {
1289 notificationManager.cancelAsUser(TAG, 0, user);
1290 return;
1291 }
1292 final Intent intent = new Intent(Settings.ACTION_VPN_SETTINGS);
1293 final PendingIntent configIntent = PendingIntent.getActivityAsUser(
1294 mContext, /* request */ 0, intent,
1295 PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT,
1296 null, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001297 final Notification.Builder builder =
1298 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1299 .setSmallIcon(R.drawable.vpn_connected)
1300 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1301 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1302 .setContentIntent(configIntent)
1303 .setCategory(Notification.CATEGORY_SYSTEM)
1304 .setVisibility(Notification.VISIBILITY_PUBLIC)
1305 .setOngoing(true)
1306 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Tony Mak1a405fe2016-06-30 11:19:20 +01001307 notificationManager.notifyAsUser(TAG, 0, builder.build(), user);
1308 } finally {
1309 Binder.restoreCallingIdentity(token);
1310 }
1311 }
1312
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001313 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001314 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001315 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001316 private native void jniReset(String interfaze);
1317 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001318 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1319 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001320
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001321 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1322 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001323 // Currently legacy VPN only works on IPv4.
1324 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001325 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001326 }
1327 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001328
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001329 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001330 }
1331
1332 /**
1333 * Start legacy VPN, controlling native daemons as needed. Creates a
1334 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001335 *
1336 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1337 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1338 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001339 */
1340 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001341 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001342 long token = Binder.clearCallingIdentity();
1343 try {
1344 startLegacyVpnPrivileged(profile, keyStore, egress);
1345 } finally {
1346 Binder.restoreCallingIdentity(token);
1347 }
1348 }
1349
1350 /**
1351 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1352 * permissions under the assumption that the caller is the system.
1353 *
1354 * Callers are responsible for checking permissions if needed.
1355 */
1356 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1357 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001358 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001359 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001360 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1361 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001362 throw new SecurityException("Restricted users cannot establish VPNs");
1363 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001364
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001365 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1366 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1367 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001368
1369 // Load certificates.
1370 String privateKey = "";
1371 String userCert = "";
1372 String caCert = "";
1373 String serverCert = "";
1374 if (!profile.ipsecUserCert.isEmpty()) {
1375 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1376 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001377 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001378 }
1379 if (!profile.ipsecCaCert.isEmpty()) {
1380 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001381 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001382 }
1383 if (!profile.ipsecServerCert.isEmpty()) {
1384 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001385 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001386 }
1387 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1388 throw new IllegalStateException("Cannot load credentials");
1389 }
1390
1391 // Prepare arguments for racoon.
1392 String[] racoon = null;
1393 switch (profile.type) {
1394 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1395 racoon = new String[] {
1396 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1397 profile.ipsecSecret, "1701",
1398 };
1399 break;
1400 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1401 racoon = new String[] {
1402 iface, profile.server, "udprsa", privateKey, userCert,
1403 caCert, serverCert, "1701",
1404 };
1405 break;
1406 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1407 racoon = new String[] {
1408 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1409 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1410 };
1411 break;
1412 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1413 racoon = new String[] {
1414 iface, profile.server, "xauthrsa", privateKey, userCert,
1415 caCert, serverCert, profile.username, profile.password, "", gateway,
1416 };
1417 break;
1418 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1419 racoon = new String[] {
1420 iface, profile.server, "hybridrsa",
1421 caCert, serverCert, profile.username, profile.password, "", gateway,
1422 };
1423 break;
1424 }
1425
1426 // Prepare arguments for mtpd.
1427 String[] mtpd = null;
1428 switch (profile.type) {
1429 case VpnProfile.TYPE_PPTP:
1430 mtpd = new String[] {
1431 iface, "pptp", profile.server, "1723",
1432 "name", profile.username, "password", profile.password,
1433 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1434 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1435 (profile.mppe ? "+mppe" : "nomppe"),
1436 };
1437 break;
1438 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1439 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1440 mtpd = new String[] {
1441 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1442 "name", profile.username, "password", profile.password,
1443 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1444 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1445 };
1446 break;
1447 }
1448
1449 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001450 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001451 config.user = profile.key;
1452 config.interfaze = iface;
1453 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001454
1455 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001456 if (!profile.dnsServers.isEmpty()) {
1457 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1458 }
1459 if (!profile.searchDomains.isEmpty()) {
1460 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1461 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001462 startLegacyVpn(config, racoon, mtpd);
1463 }
1464
1465 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001466 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001467
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001468 // Prepare for the new request.
1469 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001470 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001471
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001472 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001473 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1474 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001475 }
1476
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001477 /** Stop legacy VPN. Permissions must be checked by callers. */
1478 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001479 if (mLegacyVpnRunner != null) {
1480 mLegacyVpnRunner.exit();
1481 mLegacyVpnRunner = null;
1482
1483 synchronized (LegacyVpnRunner.TAG) {
1484 // wait for old thread to completely finish before spinning up
1485 // new instance, otherwise state updates can be out of order.
1486 }
1487 }
1488 }
1489
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001490 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001491 * Return the information of the current ongoing legacy VPN.
1492 */
1493 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001494 // Check if the caller is authorized.
1495 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001496 return getLegacyVpnInfoPrivileged();
1497 }
1498
1499 /**
1500 * Return the information of the current ongoing legacy VPN.
1501 * Callers are responsible for checking permissions if needed.
1502 */
1503 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001504 if (mLegacyVpnRunner == null) return null;
1505
1506 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001507 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001508 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001509 if (mNetworkInfo.isConnected()) {
1510 info.intent = mStatusIntent;
1511 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001512 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001513 }
1514
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001515 public VpnConfig getLegacyVpnConfig() {
1516 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001517 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001518 } else {
1519 return null;
1520 }
1521 }
1522
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001523 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001524 * Bringing up a VPN connection takes time, and that is all this thread
1525 * does. Here we have plenty of time. The only thing we need to take
1526 * care of is responding to interruptions as soon as possible. Otherwise
1527 * requests will be piled up. This can be done in a Handler as a state
1528 * machine, but it is much easier to read in the current form.
1529 */
1530 private class LegacyVpnRunner extends Thread {
1531 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001532
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001533 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001534 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001535 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001536 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001537 private final AtomicInteger mOuterConnection =
1538 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001539
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001540 private long mTimer = -1;
1541
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001542 /**
1543 * Watch for the outer connection (passing in the constructor) going away.
1544 */
1545 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1546 @Override
1547 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001548 if (!mEnableTeardown) return;
1549
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001550 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1551 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1552 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1553 NetworkInfo info = (NetworkInfo)intent.getExtra(
1554 ConnectivityManager.EXTRA_NETWORK_INFO);
1555 if (info != null && !info.isConnectedOrConnecting()) {
1556 try {
1557 mObserver.interfaceStatusChanged(mOuterInterface, false);
1558 } catch (RemoteException e) {}
1559 }
1560 }
1561 }
1562 }
1563 };
1564
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001565 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001566 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001567 mConfig = config;
1568 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001569 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001570 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001571 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001572
1573 // This is the interface which VPN is running on,
1574 // mConfig.interfaze will change to point to OUR
1575 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001576 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001577 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001578 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001579 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001580
Paul Jensene75b9e32015-04-06 11:54:53 -04001581 if (!TextUtils.isEmpty(mOuterInterface)) {
1582 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1583 for (Network network : cm.getAllNetworks()) {
1584 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001585 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001586 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1587 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1588 }
1589 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001590 }
1591
1592 IntentFilter filter = new IntentFilter();
1593 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1594 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001595 }
1596
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001597 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001598 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001599 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1600 exit();
1601 }
1602 }
1603
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001604 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001605 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001606 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001607 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001608 try {
1609 mContext.unregisterReceiver(mBroadcastReceiver);
1610 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001611 }
1612
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001613 @Override
1614 public void run() {
1615 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001616 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001617 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001618 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001619 try {
1620 execute();
1621 monitorDaemons();
1622 interrupted(); // Clear interrupt flag if execute called exit.
1623 } catch (InterruptedException e) {
1624 } finally {
1625 for (LocalSocket socket : mSockets) {
1626 IoUtils.closeQuietly(socket);
1627 }
1628 // This sleep is necessary for racoon to successfully complete sending delete
1629 // message to server.
1630 try {
1631 Thread.sleep(50);
1632 } catch (InterruptedException e) {
1633 }
1634 for (String daemon : mDaemons) {
1635 SystemService.stop(daemon);
1636 }
1637 }
1638 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001639 }
1640 }
1641
1642 private void checkpoint(boolean yield) throws InterruptedException {
1643 long now = SystemClock.elapsedRealtime();
1644 if (mTimer == -1) {
1645 mTimer = now;
1646 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001647 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001648 Thread.sleep(yield ? 200 : 1);
1649 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001650 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001651 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001652 }
1653 }
1654
1655 private void execute() {
1656 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001657 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001658 try {
1659 // Initialize the timer.
1660 checkpoint(false);
1661
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001662 // Wait for the daemons to stop.
1663 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001664 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001665 checkpoint(true);
1666 }
1667 }
1668
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001669 // Clear the previous state.
1670 File state = new File("/data/misc/vpn/state");
1671 state.delete();
1672 if (state.exists()) {
1673 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001674 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001675 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001676 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001677
Chia-chi Yehe9107902011-07-02 01:48:50 -07001678 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001679 boolean restart = false;
1680 for (String[] arguments : mArguments) {
1681 restart = restart || (arguments != null);
1682 }
1683 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001684 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001685 return;
1686 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001687 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001688
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001689 // Start the daemon with arguments.
1690 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001691 String[] arguments = mArguments[i];
1692 if (arguments == null) {
1693 continue;
1694 }
1695
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001696 // Start the daemon.
1697 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001698 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001699
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001700 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001701 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001702 checkpoint(true);
1703 }
1704
1705 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001706 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001707 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001708 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001709
1710 // Wait for the socket to connect.
1711 while (true) {
1712 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001713 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001714 break;
1715 } catch (Exception e) {
1716 // ignore
1717 }
1718 checkpoint(true);
1719 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001720 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001721
1722 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001723 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001724 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001725 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001726 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001727 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001728 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001729 out.write(bytes.length >> 8);
1730 out.write(bytes.length);
1731 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001732 checkpoint(false);
1733 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001734 out.write(0xFF);
1735 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001736 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001737
1738 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001739 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001740 while (true) {
1741 try {
1742 if (in.read() == -1) {
1743 break;
1744 }
1745 } catch (Exception e) {
1746 // ignore
1747 }
1748 checkpoint(true);
1749 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001750 }
1751
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001752 // Wait for the daemons to create the new state.
1753 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001754 // Check if a running daemon is dead.
1755 for (int i = 0; i < mDaemons.length; ++i) {
1756 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001757 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001758 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001759 }
1760 }
1761 checkpoint(true);
1762 }
1763
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001764 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001765 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001766 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001767 throw new IllegalStateException("Cannot parse the state");
1768 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001769
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001770 // Set the interface and the addresses in the config.
1771 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001772
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001773 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001774 // Set the routes if they are not set in the config.
1775 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001776 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001777 }
1778
1779 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001780 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001781 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001782 if (!dnsServers.isEmpty()) {
1783 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1784 }
1785 }
1786
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001787 // Set the search domains if they are not set in the config.
1788 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1789 String searchDomains = parameters[4].trim();
1790 if (!searchDomains.isEmpty()) {
1791 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1792 }
1793 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001794
Lorenzo Colitti50262792014-09-19 01:53:35 +09001795 // Add a throw route for the VPN server endpoint, if one was specified.
1796 String endpoint = parameters[5];
1797 if (!endpoint.isEmpty()) {
1798 try {
1799 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1800 if (addr instanceof Inet4Address) {
1801 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1802 } else if (addr instanceof Inet6Address) {
1803 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1804 } else {
1805 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1806 }
1807 } catch (IllegalArgumentException e) {
1808 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1809 }
1810 }
1811
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001812 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001813 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001814 // Set the start time
1815 mConfig.startTime = SystemClock.elapsedRealtime();
1816
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001817 // Check if the thread is interrupted while we are waiting.
1818 checkpoint(false);
1819
Chia-chi Yehe9107902011-07-02 01:48:50 -07001820 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001821 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001822 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001823 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001824
1825 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001826 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01001827 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001828
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001829 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001830
1831 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001832 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001833 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001834 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001835 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001836 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001837 }
1838 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001839
1840 /**
1841 * Monitor the daemons we started, moving to disconnected state if the
1842 * underlying services fail.
1843 */
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001844 private void monitorDaemons() throws InterruptedException{
Jeff Sharkey899223b2012-08-04 15:24:58 -07001845 if (!mNetworkInfo.isConnected()) {
1846 return;
1847 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001848 while (true) {
1849 Thread.sleep(2000);
1850 for (int i = 0; i < mDaemons.length; i++) {
1851 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1852 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001853 }
1854 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001855 }
1856 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001857 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001858}