blob: 2eb555754732b560bdf59bdb813b55a6be8bd6c0 [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;
Chris Wren282cfef2017-03-27 15:01:44 -040084import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070085import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070086import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080087import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import com.android.internal.net.VpnProfile;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050089import com.android.internal.notification.SystemNotificationChannels;
Christopher Tatee0be7e82017-02-08 17:38:20 -080090import com.android.server.DeviceIdleController;
91import com.android.server.LocalServices;
Jeff Sharkey899223b2012-08-04 15:24:58 -070092import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093
Jeff Davidson05542602014-08-11 14:07:27 -070094import libcore.io.IoUtils;
95
Chia-chi Yeh97a61562011-07-14 15:05:05 -070096import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070097import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070098import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070099import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700100import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700101import java.net.Inet6Address;
102import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -0700103import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700105import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100106import java.util.Collection;
107import java.util.Collections;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400108import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +0100109import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400110import java.util.SortedSet;
111import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700112import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700113
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700114/**
115 * @hide
116 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117public class Vpn {
118 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700119 private static final String TAG = "Vpn";
120 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400121
Christopher Tatee0be7e82017-02-08 17:38:20 -0800122 // Length of time (in milliseconds) that an app hosting an always-on VPN is placed on
123 // the device idle whitelist during service launch and VPN bootstrap.
124 private static final long VPN_LAUNCH_IDLE_WHITELIST_DURATION = 60 * 1000;
125
Jeff Sharkey899223b2012-08-04 15:24:58 -0700126 // TODO: create separate trackers for each unique VPN to support
127 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700128
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129 private Context mContext;
130 private NetworkInfo mNetworkInfo;
131 private String mPackage;
132 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700133 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700134 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700135 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700136 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700137 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400138 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700139 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400140 private NetworkAgent mNetworkAgent;
141 private final Looper mLooper;
142 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700143
Robin Lee4d03abc2016-05-09 12:32:27 +0100144 /**
Robin Lee17e61832016-05-09 13:46:28 +0100145 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
146 * only applies to {@link VpnService} connections.
147 */
148 private boolean mAlwaysOn = false;
149
150 /**
151 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
152 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
153 * not set.
154 */
155 private boolean mLockdown = false;
156
157 /**
Robin Lee4d03abc2016-05-09 12:32:27 +0100158 * List of UIDs that are set to use this VPN by default. Normally, every UID in the user is
159 * added to this set but that can be changed by adding allowed or disallowed applications. It
160 * is non-null iff the VPN is connected.
161 *
162 * Unless the VPN has set allowBypass=true, these UIDs are forced into the VPN.
163 *
164 * @see VpnService.Builder#addAllowedApplication(String)
165 * @see VpnService.Builder#addDisallowedApplication(String)
166 */
Chad Brubakerc2865192013-07-10 14:46:23 -0700167 @GuardedBy("this")
Robin Lee4d03abc2016-05-09 12:32:27 +0100168 private Set<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700169
Robin Lee17e61832016-05-09 13:46:28 +0100170 /**
171 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
172 * when VPN is not running. For example, during system startup or after a crash.
173 * @see mLockdown
174 */
175 @GuardedBy("this")
176 private Set<UidRange> mBlockedUsers = new ArraySet<>();
177
Paul Jensen0784eea2014-08-19 16:00:24 -0400178 // Handle of user initiating VPN.
179 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700180
Robin Lee812800c2016-05-13 15:38:08 +0100181 // Listen to package remove and change event in this user
182 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
183 @Override
184 public void onReceive(Context context, Intent intent) {
185 final Uri data = intent.getData();
186 final String packageName = data == null ? null : data.getSchemeSpecificPart();
187 if (packageName == null) {
188 return;
189 }
190
191 synchronized (Vpn.this) {
192 // Avoid race that always-on package has been unset
193 if (!packageName.equals(getAlwaysOnPackage())) {
194 return;
195 }
196
197 final String action = intent.getAction();
198 Log.i(TAG, "Received broadcast " + action + " for always-on package " + packageName
199 + " in user " + mUserHandle);
200
201 switch(action) {
202 case Intent.ACTION_PACKAGE_REPLACED:
203 // Start vpn after app upgrade
204 startAlwaysOnVpn();
205 break;
206 case Intent.ACTION_PACKAGE_REMOVED:
207 final boolean isPackageRemoved = !intent.getBooleanExtra(
208 Intent.EXTRA_REPLACING, false);
209 if (isPackageRemoved) {
210 setAndSaveAlwaysOnPackage(null, false);
211 }
212 break;
213 }
214 }
215 }
216 };
217
218 private boolean mIsPackageIntentReceiverRegistered = false;
219
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400220 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400221 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700222 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400223 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400224 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400225 mLooper = looper;
226
227 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400228 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700229
230 try {
231 netService.registerObserver(mObserver);
232 } catch (RemoteException e) {
233 Log.wtf(TAG, "Problem registering observer", e);
234 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400235
236 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
237 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
238 mNetworkCapabilities = new NetworkCapabilities();
239 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
240 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700241 }
242
Jeff Sharkey57666932013-04-30 17:01:57 -0700243 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700244 * Set if this object is responsible for watching for {@link NetworkInfo}
245 * teardown. When {@code false}, teardown is handled externally by someone
246 * else.
247 */
248 public void setEnableTeardown(boolean enableTeardown) {
249 mEnableTeardown = enableTeardown;
250 }
251
Jeff Sharkey899223b2012-08-04 15:24:58 -0700252 /**
253 * Update current state, dispaching event to listeners.
254 */
Tony Mak1a405fe2016-06-30 11:19:20 +0100255 @VisibleForTesting
256 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700257 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
258 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400259 if (mNetworkAgent != null) {
260 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
261 }
Tony Mak1a405fe2016-06-30 11:19:20 +0100262 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700263 }
264
265 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000266 * Configures an always-on VPN connection through a specific application.
267 * This connection is automatically granted and persisted after a reboot.
268 *
269 * <p>The designated package should exist and declare a {@link VpnService} in its
270 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
271 * otherwise the call will fail.
272 *
Robin Lee17e61832016-05-09 13:46:28 +0100273 * @param packageName the package to designate as always-on VPN supplier.
274 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100275 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000276 */
Robin Lee17e61832016-05-09 13:46:28 +0100277 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000278 enforceControlPermissionOrInternalCaller();
Robin Lee9ff1a582016-06-10 16:41:10 +0100279 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
280 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
281 return false;
282 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000283
Robin Lee244ce8e2016-01-05 18:03:46 +0000284 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100285 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000286 if (!setPackageAuthorization(packageName, true)) {
287 return false;
288 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100289 mAlwaysOn = true;
290 } else {
291 packageName = VpnConfig.LEGACY_VPN;
292 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000293 }
294
Robin Lee17e61832016-05-09 13:46:28 +0100295 mLockdown = (mAlwaysOn && lockdown);
Tony Mak1a405fe2016-06-30 11:19:20 +0100296 if (isCurrentPreparedPackage(packageName)) {
297 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
298 } else {
299 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100300 prepareInternal(packageName);
301 }
Robin Lee812800c2016-05-13 15:38:08 +0100302 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100303 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000304 return true;
305 }
306
Robin Lee9ff1a582016-06-10 16:41:10 +0100307 private static boolean isNullOrLegacyVpn(String packageName) {
308 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
309 }
310
Robin Lee812800c2016-05-13 15:38:08 +0100311 private void unregisterPackageChangeReceiverLocked() {
312 // register previous intent filter
313 if (mIsPackageIntentReceiverRegistered) {
314 mContext.unregisterReceiver(mPackageIntentReceiver);
315 mIsPackageIntentReceiverRegistered = false;
316 }
317 }
318
319 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
320 // Unregister IntentFilter listening for previous always-on package change
321 unregisterPackageChangeReceiverLocked();
322
Robin Lee9ff1a582016-06-10 16:41:10 +0100323 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100324 mIsPackageIntentReceiverRegistered = true;
325
326 IntentFilter intentFilter = new IntentFilter();
327 // Protected intent can only be sent by system. No permission required in register.
328 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
329 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
330 intentFilter.addDataScheme("package");
331 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
332 mContext.registerReceiverAsUser(
333 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
334 }
335 }
336
Robin Lee244ce8e2016-01-05 18:03:46 +0000337 /**
338 * @return the package name of the VPN controller responsible for always-on VPN,
339 * or {@code null} if none is set or always-on VPN is controlled through
340 * lockdown instead.
341 * @hide
342 */
343 public synchronized String getAlwaysOnPackage() {
344 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100345 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000346 }
347
348 /**
Robin Lee812800c2016-05-13 15:38:08 +0100349 * Save the always-on package and lockdown config into Settings.Secure
350 */
351 public synchronized void saveAlwaysOnPackage() {
352 final long token = Binder.clearCallingIdentity();
353 try {
354 final ContentResolver cr = mContext.getContentResolver();
355 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
356 getAlwaysOnPackage(), mUserHandle);
357 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
358 (mLockdown ? 1 : 0), mUserHandle);
359 } finally {
360 Binder.restoreCallingIdentity(token);
361 }
362 }
363
364 /**
365 * Set and save always-on package and lockdown config
366 * @see Vpn#setAlwaysOnPackage(String, boolean)
367 * @see Vpn#saveAlwaysOnPackage()
368 *
369 * @return result of Vpn#setAndSaveAlwaysOnPackage(String, boolean)
370 */
371 private synchronized boolean setAndSaveAlwaysOnPackage(String packageName, boolean lockdown) {
372 if (setAlwaysOnPackage(packageName, lockdown)) {
373 saveAlwaysOnPackage();
374 return true;
375 } else {
376 return false;
377 }
378 }
379
380 /**
381 * @return {@code true} if the service was started, the service was already connected, or there
382 * was no always-on VPN to start. {@code false} otherwise.
383 */
384 public boolean startAlwaysOnVpn() {
385 final String alwaysOnPackage;
386 synchronized (this) {
387 alwaysOnPackage = getAlwaysOnPackage();
388 // Skip if there is no service to start.
389 if (alwaysOnPackage == null) {
390 return true;
391 }
392 // Skip if the service is already established. This isn't bulletproof: it's not bound
393 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
394 // which may restart the connection.
395 if (getNetworkInfo().isConnected()) {
396 return true;
397 }
398 }
399
Christopher Tatee0be7e82017-02-08 17:38:20 -0800400 // Tell the OS that background services in this app need to be allowed for
401 // a short time, so we can bootstrap the VPN service.
402 final long oldId = Binder.clearCallingIdentity();
Robin Lee812800c2016-05-13 15:38:08 +0100403 try {
Christopher Tatee0be7e82017-02-08 17:38:20 -0800404 DeviceIdleController.LocalService idleController =
405 LocalServices.getService(DeviceIdleController.LocalService.class);
406 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
407 VPN_LAUNCH_IDLE_WHITELIST_DURATION, mUserHandle, false, "vpn");
408
409 // Start the VPN service declared in the app's manifest.
410 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
411 serviceIntent.setPackage(alwaysOnPackage);
412 try {
413 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
414 } catch (RuntimeException e) {
415 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
416 return false;
417 }
418 } finally {
419 Binder.restoreCallingIdentity(oldId);
Robin Lee812800c2016-05-13 15:38:08 +0100420 }
421 }
422
423 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700424 * Prepare for a VPN application. This method is designed to solve
425 * race conditions. It first compares the current prepared package
426 * with {@code oldPackage}. If they are the same, the prepared
427 * package is revoked and replaced with {@code newPackage}. If
428 * {@code oldPackage} is {@code null}, the comparison is omitted.
429 * If {@code newPackage} is the same package or {@code null}, the
430 * revocation is omitted. This method returns {@code true} if the
431 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700432 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700433 * Legacy VPN is handled specially since it is not a real package.
434 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
435 * it can be revoked by itself.
436 *
Victor Chang98a633a2016-05-27 17:30:49 +0100437 * Note: when we added VPN pre-consent in http://ag/522961 the names oldPackage
438 * and newPackage become misleading, because when an app is pre-consented, we
439 * actually prepare oldPackage, not newPackage.
440 *
441 * Their meanings actually are:
442 *
443 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
444 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100445 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100446 * and revoke any current app VPN and re-prepare legacy vpn.
447 *
Robin Lee812800c2016-05-13 15:38:08 +0100448 * TODO: Rename the variables - or split this method into two - and end this confusion.
449 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
450 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100451 *
452 * @param oldPackage The package name of the old VPN application
453 * @param newPackage The package name of the new VPN application
454 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700455 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700456 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700457 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700458 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100459 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100460 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100461 return false;
462 }
463
464 // Package is not same or old package was reinstalled.
465 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700466 // The package doesn't match. We return false (to obtain user consent) unless the
467 // user has already consented to that VPN package.
468 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
469 prepareInternal(oldPackage);
470 return true;
471 }
472 return false;
473 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
474 && !isVpnUserPreConsented(oldPackage)) {
475 // Currently prepared VPN is revoked, so unprepare it and return false.
476 prepareInternal(VpnConfig.LEGACY_VPN);
477 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700478 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700479 }
480
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700481 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700482 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100483 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700484 return true;
485 }
486
Robin Lee1b1bcd72016-02-12 18:11:30 +0000487 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700488 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700489
Victor Chang98a633a2016-05-27 17:30:49 +0100490 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100491 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100492 return false;
493 }
494
Jeff Davidson11008a72014-11-20 13:12:46 -0800495 prepareInternal(newPackage);
496 return true;
497 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700498
Victor Chang98a633a2016-05-27 17:30:49 +0100499 private boolean isCurrentPreparedPackage(String packageName) {
500 // We can't just check that packageName matches mPackage, because if the app was uninstalled
501 // and reinstalled it will no longer be prepared. Instead check the UID.
502 return getAppUid(packageName, mUserHandle) == mOwnerUID;
503 }
504
Jeff Davidson11008a72014-11-20 13:12:46 -0800505 /** Prepare the VPN for the given package. Does not perform permission checks. */
506 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400507 long token = Binder.clearCallingIdentity();
508 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800509 // Reset the interface.
510 if (mInterface != null) {
511 mStatusIntent = null;
512 agentDisconnect();
513 jniReset(mInterface);
514 mInterface = null;
515 mVpnUsers = null;
516 }
517
518 // Revoke the connection or stop LegacyVpnRunner.
519 if (mConnection != null) {
520 try {
521 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
522 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
523 } catch (Exception e) {
524 // ignore
525 }
526 mContext.unbindService(mConnection);
527 mConnection = null;
528 } else if (mLegacyVpnRunner != null) {
529 mLegacyVpnRunner.exit();
530 mLegacyVpnRunner = null;
531 }
532
533 try {
534 mNetd.denyProtect(mOwnerUID);
535 } catch (Exception e) {
536 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
537 }
538
539 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
540 mPackage = newPackage;
541 mOwnerUID = getAppUid(newPackage, mUserHandle);
542 try {
543 mNetd.allowProtect(mOwnerUID);
544 } catch (Exception e) {
545 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
546 }
547 mConfig = null;
548
549 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400550 } finally {
551 Binder.restoreCallingIdentity(token);
552 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700553 }
554
Jeff Davidson05542602014-08-11 14:07:27 -0700555 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100556 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700557 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000558 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700559 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000560 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700561
Robin Lee3b3dd942015-05-12 18:14:58 +0100562 int uid = getAppUid(packageName, mUserHandle);
563 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
564 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000565 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700566 }
567
568 long token = Binder.clearCallingIdentity();
569 try {
570 AppOpsManager appOps =
571 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100572 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700573 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000574 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700575 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100576 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700577 } finally {
578 Binder.restoreCallingIdentity(token);
579 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000580 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700581 }
582
583 private boolean isVpnUserPreConsented(String packageName) {
584 AppOpsManager appOps =
585 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
586
587 // Verify that the caller matches the given package and has permission to activate VPNs.
588 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
589 packageName) == AppOpsManager.MODE_ALLOWED;
590 }
591
Paul Jensen0784eea2014-08-19 16:00:24 -0400592 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700593 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400594 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700595 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400596 PackageManager pm = mContext.getPackageManager();
597 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700598 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700599 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400600 } catch (NameNotFoundException e) {
601 result = -1;
602 }
603 return result;
604 }
605
606 public NetworkInfo getNetworkInfo() {
607 return mNetworkInfo;
608 }
609
Paul Jensen31a94f42015-02-13 14:18:39 -0500610 public int getNetId() {
611 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
612 }
613
Lorenzo Colitti60446162014-09-20 00:14:31 +0900614 private LinkProperties makeLinkProperties() {
615 boolean allowIPv4 = mConfig.allowIPv4;
616 boolean allowIPv6 = mConfig.allowIPv6;
617
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400618 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900619
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400620 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700621
Lorenzo Colitti60446162014-09-20 00:14:31 +0900622 if (mConfig.addresses != null) {
623 for (LinkAddress address : mConfig.addresses) {
624 lp.addLinkAddress(address);
625 allowIPv4 |= address.getAddress() instanceof Inet4Address;
626 allowIPv6 |= address.getAddress() instanceof Inet6Address;
627 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400628 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900629
630 if (mConfig.routes != null) {
631 for (RouteInfo route : mConfig.routes) {
632 lp.addRoute(route);
633 InetAddress address = route.getDestination().getAddress();
634 allowIPv4 |= address instanceof Inet4Address;
635 allowIPv6 |= address instanceof Inet6Address;
636 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400637 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700638
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400639 if (mConfig.dnsServers != null) {
640 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700641 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
642 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900643 allowIPv4 |= address instanceof Inet4Address;
644 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400645 }
646 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700647
Lorenzo Colitti60446162014-09-20 00:14:31 +0900648 if (!allowIPv4) {
649 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
650 }
651 if (!allowIPv6) {
652 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
653 }
654
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400655 // Concatenate search domains into a string.
656 StringBuilder buffer = new StringBuilder();
657 if (mConfig.searchDomains != null) {
658 for (String domain : mConfig.searchDomains) {
659 buffer.append(domain).append(' ');
660 }
661 }
662 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700663
Lorenzo Colitti60446162014-09-20 00:14:31 +0900664 // TODO: Stop setting the MTU in jniCreate and set it here.
665
666 return lp;
667 }
668
669 private void agentConnect() {
670 LinkProperties lp = makeLinkProperties();
671
672 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
673 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
674 } else {
675 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
676 }
677
Robin Lee323f29d2016-05-04 16:38:06 +0100678 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700679
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700680 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100681 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700682
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400683 long token = Binder.clearCallingIdentity();
684 try {
685 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700686 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700687 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400688 public void unwanted() {
689 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700690 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400691 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700692 } finally {
693 Binder.restoreCallingIdentity(token);
694 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700695
Robin Lee4d03abc2016-05-09 12:32:27 +0100696 mVpnUsers = createUserAndRestrictedProfilesRanges(mUserHandle,
697 mConfig.allowedApplications, mConfig.disallowedApplications);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400698 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
Robin Lee323f29d2016-05-04 16:38:06 +0100699
700 mNetworkInfo.setIsAvailable(true);
701 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400702 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700703
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700704 private boolean canHaveRestrictedProfile(int userId) {
705 long token = Binder.clearCallingIdentity();
706 try {
707 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
708 } finally {
709 Binder.restoreCallingIdentity(token);
710 }
711 }
712
Tony Mak1a405fe2016-06-30 11:19:20 +0100713 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400714 if (networkAgent != null) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100715 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
716 networkInfo.setIsAvailable(false);
717 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400718 networkAgent.sendNetworkInfo(networkInfo);
719 }
720 }
721
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400722 private void agentDisconnect() {
723 if (mNetworkInfo.isConnected()) {
Tony Mak1a405fe2016-06-30 11:19:20 +0100724 mNetworkInfo.setIsAvailable(false);
725 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400726 mNetworkAgent = null;
727 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700728 }
729
730 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700731 * Establish a VPN network and return the file descriptor of the VPN
732 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700733 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700734 *
735 * @param config The parameters to configure the network.
736 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700737 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700738 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700739 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700740 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400741 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700742 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700743 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700744 // Check to ensure consent hasn't been revoked since we were prepared.
745 if (!isVpnUserPreConsented(mPackage)) {
746 return null;
747 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700748 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700749 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
750 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700751 long token = Binder.clearCallingIdentity();
752 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700753 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400754 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100755 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700756 throw new SecurityException("Restricted users cannot establish VPNs");
757 }
758
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700759 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400760 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700761 if (info == null) {
762 throw new SecurityException("Cannot find " + config.user);
763 }
764 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
765 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
766 }
767 } catch (RemoteException e) {
768 throw new SecurityException("Cannot find " + config.user);
769 } finally {
770 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700771 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700772
Chad Brubaker850eb672014-03-21 21:02:47 +0000773 // Save the old config in case we need to go back.
774 VpnConfig oldConfig = mConfig;
775 String oldInterface = mInterface;
776 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400777 NetworkAgent oldNetworkAgent = mNetworkAgent;
778 mNetworkAgent = null;
Robin Lee4d03abc2016-05-09 12:32:27 +0100779 Set<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000780
Chia-chi Yehe9107902011-07-02 01:48:50 -0700781 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700782 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700783 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700784 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700785 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700786
Chad Brubakerc2865192013-07-10 14:46:23 -0700787 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700788 StringBuilder builder = new StringBuilder();
789 for (LinkAddress address : config.addresses) {
790 builder.append(" " + address);
791 }
792 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700793 throw new IllegalArgumentException("At least one address must be specified");
794 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700795 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700796 if (!mContext.bindServiceAsUser(intent, connection,
797 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
798 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700799 throw new IllegalStateException("Cannot bind " + config.user);
800 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000801
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700802 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700803 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700804
805 // Fill more values.
806 config.user = mPackage;
807 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700808 config.startTime = SystemClock.elapsedRealtime();
809 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000810
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700811 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400812 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000813
814 if (oldConnection != null) {
815 mContext.unbindService(oldConnection);
816 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400817 // Remove the old tun's user forwarding rules
818 // The new tun's user rules have already been added so they will take over
819 // as rules are deleted. This prevents data leakage as the rules are moved over.
820 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000821 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000822 jniReset(oldInterface);
823 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700824
825 try {
826 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
827 } catch (IOException e) {
828 throw new IllegalStateException(
829 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
830 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000831 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000832 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400833 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000834 // restore old state
835 mConfig = oldConfig;
836 mConnection = oldConnection;
837 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400838 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000839 mInterface = oldInterface;
840 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700841 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000842 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700843 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700844 }
845
Chad Brubakerc2865192013-07-10 14:46:23 -0700846 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800847 return mNetworkAgent != null && mInterface != null;
848 }
849
850 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
851 // that a call to mutate VPN state is admissible.
852 private boolean isCallerEstablishedOwnerLocked() {
853 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700854 }
855
Paul Jensen0784eea2014-08-19 16:00:24 -0400856 // Note: Return type guarantees results are deduped and sorted, which callers require.
857 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
858 SortedSet<Integer> uids = new TreeSet<Integer>();
859 for (String app : packageNames) {
860 int uid = getAppUid(app, userHandle);
861 if (uid != -1) uids.add(uid);
862 }
863 return uids;
864 }
865
Robin Lee4d03abc2016-05-09 12:32:27 +0100866 /**
867 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
868 * associated with one user, and any restricted profiles attached to that user.
869 *
870 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
871 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
872 * in each user and profile will be included.
873 *
874 * @param userHandle The userId to create UID ranges for along with any of its restricted
875 * profiles.
876 * @param allowedApplications (optional) whitelist of applications to include.
877 * @param disallowedApplications (optional) blacklist of applications to exclude.
878 */
879 @VisibleForTesting
880 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
881 @Nullable List<String> allowedApplications,
882 @Nullable List<String> disallowedApplications) {
883 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700884
Robin Lee4d03abc2016-05-09 12:32:27 +0100885 // Assign the top-level user to the set of ranges
886 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
887
888 // If the user can have restricted profiles, assign all its restricted profiles too
889 if (canHaveRestrictedProfile(userHandle)) {
890 final long token = Binder.clearCallingIdentity();
891 List<UserInfo> users;
892 try {
Robin Lee17e61832016-05-09 13:46:28 +0100893 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +0100894 } finally {
895 Binder.restoreCallingIdentity(token);
896 }
897 for (UserInfo user : users) {
898 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
899 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
900 }
901 }
902 }
903 return ranges;
904 }
905
906 /**
907 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
908 * associated with one user.
909 *
910 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
911 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
912 * in the user will be included.
913 *
914 * @param ranges {@link Set} of {@link UidRange}s to which to add.
915 * @param userHandle The userId to add to {@param ranges}.
916 * @param allowedApplications (optional) whitelist of applications to include.
917 * @param disallowedApplications (optional) blacklist of applications to exclude.
918 */
919 @VisibleForTesting
920 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
921 @Nullable List<String> allowedApplications,
922 @Nullable List<String> disallowedApplications) {
923 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400924 // Add ranges covering all UIDs for allowedApplications.
925 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +0100926 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400927 if (start == -1) {
928 start = uid;
929 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100930 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400931 start = uid;
932 }
933 stop = uid;
934 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100935 if (start != -1) ranges.add(new UidRange(start, stop));
936 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400937 // Add all ranges for user skipping UIDs for disallowedApplications.
938 final UidRange userRange = UidRange.createForUser(userHandle);
939 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +0100940 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400941 if (uid == start) {
942 start++;
943 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +0100944 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -0400945 start = uid + 1;
946 }
947 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100948 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400949 } else {
950 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +0100951 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -0400952 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700953 }
954
Paul Jensen0784eea2014-08-19 16:00:24 -0400955 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
956 // apply to userHandle.
957 private List<UidRange> uidRangesForUser(int userHandle) {
958 final UidRange userRange = UidRange.createForUser(userHandle);
959 final List<UidRange> ranges = new ArrayList<UidRange>();
960 for (UidRange range : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100961 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400962 ranges.add(range);
963 }
964 }
965 return ranges;
966 }
967
968 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800969 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700970 throw new IllegalStateException("VPN is not active");
971 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400972 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700973 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400974 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700975 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400976 mVpnUsers.removeAll(ranges);
Chad Brubakerc2865192013-07-10 14:46:23 -0700977 }
978
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700979 public void onUserAdded(int userHandle) {
980 // If the user is restricted tie them to the parent user's VPN
981 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100982 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700983 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100984 if (mVpnUsers != null) {
985 try {
986 addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
987 mConfig.disallowedApplications);
988 if (mNetworkAgent != null) {
989 final List<UidRange> ranges = uidRangesForUser(userHandle);
990 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
991 }
992 } catch (Exception e) {
993 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400994 }
Robin Lee17e61832016-05-09 13:46:28 +0100995 }
996 if (mAlwaysOn) {
997 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700998 }
999 }
1000 }
1001 }
1002
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001003 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001004 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001005 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +01001006 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001007 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +01001008 if (mVpnUsers != null) {
1009 try {
1010 removeVpnUserLocked(userHandle);
1011 } catch (Exception e) {
1012 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
1013 }
1014 }
1015 if (mAlwaysOn) {
1016 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -07001017 }
1018 }
1019 }
1020 }
1021
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001022 /**
Robin Lee17e61832016-05-09 13:46:28 +01001023 * Called when the user associated with this VPN has just been stopped.
1024 */
1025 public synchronized void onUserStopped() {
1026 // Switch off networking lockdown (if it was enabled)
1027 setVpnForcedLocked(false);
1028 mAlwaysOn = false;
1029
Robin Lee812800c2016-05-13 15:38:08 +01001030 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001031 // Quit any active connections
1032 agentDisconnect();
1033 }
1034
1035 /**
1036 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1037 * service app itself, to only sockets that have had {@code protect()} called on them. All
1038 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1039 *
1040 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1041 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1042 *
1043 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1044 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1045 *
1046 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1047 * {@link Vpn} goes through a VPN connection or is blocked until one is
1048 * available, {@code false} to lift the requirement.
1049 *
1050 * @see #mBlockedUsers
1051 */
1052 @GuardedBy("this")
1053 private void setVpnForcedLocked(boolean enforce) {
1054 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
1055 if (enforce) {
1056 final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
1057 /* allowedApplications */ null,
1058 /* disallowedApplications */ Collections.singletonList(mPackage));
1059
1060 removedRanges.removeAll(addedRanges);
1061 addedRanges.removeAll(mBlockedUsers);
1062
1063 setAllowOnlyVpnForUids(false, removedRanges);
1064 setAllowOnlyVpnForUids(true, addedRanges);
1065 } else {
1066 setAllowOnlyVpnForUids(false, removedRanges);
1067 }
1068 }
1069
1070 /**
1071 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1072 * to make connections through sockets that have had {@code protect()} called on them.
1073 *
1074 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1075 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1076 * {@code true}) or to remove.
1077 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1078 * including added ranges that already existed or removed ones that didn't.
1079 */
1080 @GuardedBy("this")
1081 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1082 if (ranges.size() == 0) {
1083 return true;
1084 }
1085 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1086 try {
1087 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1088 } catch (RemoteException | RuntimeException e) {
1089 Log.e(TAG, "Updating blocked=" + enforce
1090 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1091 return false;
1092 }
1093 if (enforce) {
1094 mBlockedUsers.addAll(ranges);
1095 } else {
1096 mBlockedUsers.removeAll(ranges);
1097 }
1098 return true;
1099 }
1100
1101 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001102 * Return the configuration of the currently running VPN.
1103 */
1104 public VpnConfig getVpnConfig() {
1105 enforceControlPermission();
1106 return mConfig;
1107 }
1108
Jeff Sharkey899223b2012-08-04 15:24:58 -07001109 @Deprecated
1110 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1111 try {
1112 mObserver.interfaceStatusChanged(iface, up);
1113 } catch (RemoteException e) {
1114 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001115 }
1116 }
1117
Jeff Sharkey899223b2012-08-04 15:24:58 -07001118 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1119 @Override
1120 public void interfaceStatusChanged(String interfaze, boolean up) {
1121 synchronized (Vpn.this) {
1122 if (!up && mLegacyVpnRunner != null) {
1123 mLegacyVpnRunner.check(interfaze);
1124 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001125 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001126 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001127
Jeff Sharkey899223b2012-08-04 15:24:58 -07001128 @Override
1129 public void interfaceRemoved(String interfaze) {
1130 synchronized (Vpn.this) {
1131 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001132 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001133 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -05001134 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001135 mInterface = null;
1136 if (mConnection != null) {
1137 mContext.unbindService(mConnection);
1138 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001139 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001140 } else if (mLegacyVpnRunner != null) {
1141 mLegacyVpnRunner.exit();
1142 mLegacyVpnRunner = null;
1143 }
1144 }
1145 }
1146 }
1147 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001148
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001149 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001150 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001151 }
1152
Robin Lee244ce8e2016-01-05 18:03:46 +00001153 private void enforceControlPermissionOrInternalCaller() {
1154 // Require caller to be either an application with CONTROL_VPN permission or a process
1155 // in the system server.
1156 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1157 "Unauthorized Caller");
1158 }
1159
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001160 private class Connection implements ServiceConnection {
1161 private IBinder mService;
1162
1163 @Override
1164 public void onServiceConnected(ComponentName name, IBinder service) {
1165 mService = service;
1166 }
1167
1168 @Override
1169 public void onServiceDisconnected(ComponentName name) {
1170 mService = null;
1171 }
1172 }
1173
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001174 private void prepareStatusIntent() {
1175 final long token = Binder.clearCallingIdentity();
1176 try {
1177 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1178 } finally {
1179 Binder.restoreCallingIdentity(token);
1180 }
1181 }
1182
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001183 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001184 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001185 return false;
1186 }
1187 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001188 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001189 return success;
1190 }
1191
1192 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001193 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001194 return false;
1195 }
1196 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001197 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001198 return success;
1199 }
1200
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001201 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1202 if (!isCallerEstablishedOwnerLocked()) {
1203 return false;
1204 }
1205 if (networks == null) {
1206 mConfig.underlyingNetworks = null;
1207 } else {
1208 mConfig.underlyingNetworks = new Network[networks.length];
1209 for (int i = 0; i < networks.length; ++i) {
1210 if (networks[i] == null) {
1211 mConfig.underlyingNetworks[i] = null;
1212 } else {
1213 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1214 }
1215 }
1216 }
1217 return true;
1218 }
1219
1220 public synchronized Network[] getUnderlyingNetworks() {
1221 if (!isRunningLocked()) {
1222 return null;
1223 }
1224 return mConfig.underlyingNetworks;
1225 }
1226
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001227 /**
1228 * This method should only be called by ConnectivityService. Because it doesn't
1229 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1230 */
1231 public synchronized VpnInfo getVpnInfo() {
1232 if (!isRunningLocked()) {
1233 return null;
1234 }
1235
1236 VpnInfo info = new VpnInfo();
1237 info.ownerUid = mOwnerUID;
1238 info.vpnIface = mInterface;
1239 return info;
1240 }
1241
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001242 public synchronized boolean appliesToUid(int uid) {
1243 if (!isRunningLocked()) {
1244 return false;
1245 }
1246 for (UidRange uidRange : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001247 if (uidRange.contains(uid)) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001248 return true;
1249 }
1250 }
1251 return false;
1252 }
1253
Robin Lee17e61832016-05-09 13:46:28 +01001254 /**
Robin Leeebbcb542016-05-24 16:35:10 +01001255 * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1256 * A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1257 * not connected, or if the VPN is connected but does not apply to the UID.
Robin Lee17e61832016-05-09 13:46:28 +01001258 *
1259 * @see #mBlockedUsers
1260 */
1261 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001262 if (!mLockdown) {
1263 return false;
Robin Lee17e61832016-05-09 13:46:28 +01001264 }
Robin Leeebbcb542016-05-24 16:35:10 +01001265
1266 if (mNetworkInfo.isConnected()) {
1267 return !appliesToUid(uid);
1268 } else {
1269 for (UidRange uidRange : mBlockedUsers) {
1270 if (uidRange.contains(uid)) {
1271 return true;
1272 }
1273 }
1274 return false;
1275 }
Robin Lee17e61832016-05-09 13:46:28 +01001276 }
1277
Tony Mak1a405fe2016-06-30 11:19:20 +01001278 private void updateAlwaysOnNotification(DetailedState networkState) {
1279 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
1280 updateAlwaysOnNotificationInternal(visible);
1281 }
1282
1283 @VisibleForTesting
1284 protected void updateAlwaysOnNotificationInternal(boolean visible) {
1285 final UserHandle user = UserHandle.of(mUserHandle);
1286 final long token = Binder.clearCallingIdentity();
1287 try {
1288 final NotificationManager notificationManager = NotificationManager.from(mContext);
1289 if (!visible) {
1290 notificationManager.cancelAsUser(TAG, 0, user);
1291 return;
1292 }
1293 final Intent intent = new Intent(Settings.ACTION_VPN_SETTINGS);
1294 final PendingIntent configIntent = PendingIntent.getActivityAsUser(
1295 mContext, /* request */ 0, intent,
1296 PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT,
1297 null, user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001298 final Notification.Builder builder =
1299 new Notification.Builder(mContext, SystemNotificationChannels.VPN)
1300 .setSmallIcon(R.drawable.vpn_connected)
1301 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1302 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1303 .setContentIntent(configIntent)
1304 .setCategory(Notification.CATEGORY_SYSTEM)
1305 .setVisibility(Notification.VISIBILITY_PUBLIC)
1306 .setOngoing(true)
1307 .setColor(mContext.getColor(R.color.system_notification_accent_color));
Chris Wren282cfef2017-03-27 15:01:44 -04001308 notificationManager.notifyAsUser(TAG, SystemMessage.NOTE_VPN_DISCONNECTED,
1309 builder.build(), user);
Tony Mak1a405fe2016-06-30 11:19:20 +01001310 } finally {
1311 Binder.restoreCallingIdentity(token);
1312 }
1313 }
1314
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001315 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001316 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001317 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001318 private native void jniReset(String interfaze);
1319 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001320 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1321 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001322
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001323 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1324 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001325 // Currently legacy VPN only works on IPv4.
1326 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001327 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001328 }
1329 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001330
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001331 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001332 }
1333
1334 /**
1335 * Start legacy VPN, controlling native daemons as needed. Creates a
1336 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001337 *
1338 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1339 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1340 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001341 */
1342 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001343 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001344 long token = Binder.clearCallingIdentity();
1345 try {
1346 startLegacyVpnPrivileged(profile, keyStore, egress);
1347 } finally {
1348 Binder.restoreCallingIdentity(token);
1349 }
1350 }
1351
1352 /**
1353 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1354 * permissions under the assumption that the caller is the system.
1355 *
1356 * Callers are responsible for checking permissions if needed.
1357 */
1358 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1359 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001360 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001361 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001362 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1363 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001364 throw new SecurityException("Restricted users cannot establish VPNs");
1365 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001366
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001367 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1368 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1369 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001370
1371 // Load certificates.
1372 String privateKey = "";
1373 String userCert = "";
1374 String caCert = "";
1375 String serverCert = "";
1376 if (!profile.ipsecUserCert.isEmpty()) {
1377 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1378 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001379 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001380 }
1381 if (!profile.ipsecCaCert.isEmpty()) {
1382 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001383 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001384 }
1385 if (!profile.ipsecServerCert.isEmpty()) {
1386 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001387 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001388 }
1389 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1390 throw new IllegalStateException("Cannot load credentials");
1391 }
1392
1393 // Prepare arguments for racoon.
1394 String[] racoon = null;
1395 switch (profile.type) {
1396 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1397 racoon = new String[] {
1398 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1399 profile.ipsecSecret, "1701",
1400 };
1401 break;
1402 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1403 racoon = new String[] {
1404 iface, profile.server, "udprsa", privateKey, userCert,
1405 caCert, serverCert, "1701",
1406 };
1407 break;
1408 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1409 racoon = new String[] {
1410 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1411 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1412 };
1413 break;
1414 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1415 racoon = new String[] {
1416 iface, profile.server, "xauthrsa", privateKey, userCert,
1417 caCert, serverCert, profile.username, profile.password, "", gateway,
1418 };
1419 break;
1420 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1421 racoon = new String[] {
1422 iface, profile.server, "hybridrsa",
1423 caCert, serverCert, profile.username, profile.password, "", gateway,
1424 };
1425 break;
1426 }
1427
1428 // Prepare arguments for mtpd.
1429 String[] mtpd = null;
1430 switch (profile.type) {
1431 case VpnProfile.TYPE_PPTP:
1432 mtpd = new String[] {
1433 iface, "pptp", profile.server, "1723",
1434 "name", profile.username, "password", profile.password,
1435 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1436 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1437 (profile.mppe ? "+mppe" : "nomppe"),
1438 };
1439 break;
1440 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1441 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1442 mtpd = new String[] {
1443 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1444 "name", profile.username, "password", profile.password,
1445 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1446 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1447 };
1448 break;
1449 }
1450
1451 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001452 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001453 config.user = profile.key;
1454 config.interfaze = iface;
1455 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001456
1457 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001458 if (!profile.dnsServers.isEmpty()) {
1459 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1460 }
1461 if (!profile.searchDomains.isEmpty()) {
1462 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1463 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001464 startLegacyVpn(config, racoon, mtpd);
1465 }
1466
1467 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001468 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001469
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001470 // Prepare for the new request.
1471 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001472 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001473
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001474 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001475 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1476 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001477 }
1478
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001479 /** Stop legacy VPN. Permissions must be checked by callers. */
1480 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001481 if (mLegacyVpnRunner != null) {
1482 mLegacyVpnRunner.exit();
1483 mLegacyVpnRunner = null;
1484
1485 synchronized (LegacyVpnRunner.TAG) {
1486 // wait for old thread to completely finish before spinning up
1487 // new instance, otherwise state updates can be out of order.
1488 }
1489 }
1490 }
1491
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001492 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001493 * Return the information of the current ongoing legacy VPN.
1494 */
1495 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001496 // Check if the caller is authorized.
1497 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001498 return getLegacyVpnInfoPrivileged();
1499 }
1500
1501 /**
1502 * Return the information of the current ongoing legacy VPN.
1503 * Callers are responsible for checking permissions if needed.
1504 */
1505 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001506 if (mLegacyVpnRunner == null) return null;
1507
1508 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001509 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001510 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001511 if (mNetworkInfo.isConnected()) {
1512 info.intent = mStatusIntent;
1513 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001514 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001515 }
1516
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001517 public VpnConfig getLegacyVpnConfig() {
1518 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001519 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001520 } else {
1521 return null;
1522 }
1523 }
1524
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001525 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001526 * Bringing up a VPN connection takes time, and that is all this thread
1527 * does. Here we have plenty of time. The only thing we need to take
1528 * care of is responding to interruptions as soon as possible. Otherwise
1529 * requests will be piled up. This can be done in a Handler as a state
1530 * machine, but it is much easier to read in the current form.
1531 */
1532 private class LegacyVpnRunner extends Thread {
1533 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001534
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001535 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001536 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001537 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001538 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001539 private final AtomicInteger mOuterConnection =
1540 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001541
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001542 private long mTimer = -1;
1543
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001544 /**
1545 * Watch for the outer connection (passing in the constructor) going away.
1546 */
1547 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1548 @Override
1549 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001550 if (!mEnableTeardown) return;
1551
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001552 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1553 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1554 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1555 NetworkInfo info = (NetworkInfo)intent.getExtra(
1556 ConnectivityManager.EXTRA_NETWORK_INFO);
1557 if (info != null && !info.isConnectedOrConnecting()) {
1558 try {
1559 mObserver.interfaceStatusChanged(mOuterInterface, false);
1560 } catch (RemoteException e) {}
1561 }
1562 }
1563 }
1564 }
1565 };
1566
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001567 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001568 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001569 mConfig = config;
1570 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001571 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001572 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001573 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001574
1575 // This is the interface which VPN is running on,
1576 // mConfig.interfaze will change to point to OUR
1577 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001578 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001579 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001580 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001581 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001582
Paul Jensene75b9e32015-04-06 11:54:53 -04001583 if (!TextUtils.isEmpty(mOuterInterface)) {
1584 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1585 for (Network network : cm.getAllNetworks()) {
1586 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001587 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001588 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1589 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1590 }
1591 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001592 }
1593
1594 IntentFilter filter = new IntentFilter();
1595 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1596 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001597 }
1598
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001599 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001600 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001601 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1602 exit();
1603 }
1604 }
1605
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001606 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001607 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001608 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001609 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001610 try {
1611 mContext.unregisterReceiver(mBroadcastReceiver);
1612 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001613 }
1614
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001615 @Override
1616 public void run() {
1617 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001618 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001619 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001620 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001621 try {
1622 execute();
1623 monitorDaemons();
1624 interrupted(); // Clear interrupt flag if execute called exit.
1625 } catch (InterruptedException e) {
1626 } finally {
1627 for (LocalSocket socket : mSockets) {
1628 IoUtils.closeQuietly(socket);
1629 }
1630 // This sleep is necessary for racoon to successfully complete sending delete
1631 // message to server.
1632 try {
1633 Thread.sleep(50);
1634 } catch (InterruptedException e) {
1635 }
1636 for (String daemon : mDaemons) {
1637 SystemService.stop(daemon);
1638 }
1639 }
1640 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001641 }
1642 }
1643
1644 private void checkpoint(boolean yield) throws InterruptedException {
1645 long now = SystemClock.elapsedRealtime();
1646 if (mTimer == -1) {
1647 mTimer = now;
1648 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001649 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001650 Thread.sleep(yield ? 200 : 1);
1651 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001652 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001653 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001654 }
1655 }
1656
1657 private void execute() {
1658 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001659 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001660 try {
1661 // Initialize the timer.
1662 checkpoint(false);
1663
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001664 // Wait for the daemons to stop.
1665 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001666 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001667 checkpoint(true);
1668 }
1669 }
1670
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001671 // Clear the previous state.
1672 File state = new File("/data/misc/vpn/state");
1673 state.delete();
1674 if (state.exists()) {
1675 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001676 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001677 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001678 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001679
Chia-chi Yehe9107902011-07-02 01:48:50 -07001680 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001681 boolean restart = false;
1682 for (String[] arguments : mArguments) {
1683 restart = restart || (arguments != null);
1684 }
1685 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001686 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001687 return;
1688 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001689 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001690
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001691 // Start the daemon with arguments.
1692 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001693 String[] arguments = mArguments[i];
1694 if (arguments == null) {
1695 continue;
1696 }
1697
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001698 // Start the daemon.
1699 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001700 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001701
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001702 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001703 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001704 checkpoint(true);
1705 }
1706
1707 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001708 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001709 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001710 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001711
1712 // Wait for the socket to connect.
1713 while (true) {
1714 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001715 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001716 break;
1717 } catch (Exception e) {
1718 // ignore
1719 }
1720 checkpoint(true);
1721 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001722 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001723
1724 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001725 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001726 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001727 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001728 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001729 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001730 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001731 out.write(bytes.length >> 8);
1732 out.write(bytes.length);
1733 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001734 checkpoint(false);
1735 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001736 out.write(0xFF);
1737 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001738 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001739
1740 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001741 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001742 while (true) {
1743 try {
1744 if (in.read() == -1) {
1745 break;
1746 }
1747 } catch (Exception e) {
1748 // ignore
1749 }
1750 checkpoint(true);
1751 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001752 }
1753
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001754 // Wait for the daemons to create the new state.
1755 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001756 // Check if a running daemon is dead.
1757 for (int i = 0; i < mDaemons.length; ++i) {
1758 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001759 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001760 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001761 }
1762 }
1763 checkpoint(true);
1764 }
1765
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001766 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001767 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001768 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001769 throw new IllegalStateException("Cannot parse the state");
1770 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001771
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001772 // Set the interface and the addresses in the config.
1773 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001774
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001775 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001776 // Set the routes if they are not set in the config.
1777 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001778 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001779 }
1780
1781 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001782 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001783 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001784 if (!dnsServers.isEmpty()) {
1785 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1786 }
1787 }
1788
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001789 // Set the search domains if they are not set in the config.
1790 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1791 String searchDomains = parameters[4].trim();
1792 if (!searchDomains.isEmpty()) {
1793 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1794 }
1795 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001796
Lorenzo Colitti50262792014-09-19 01:53:35 +09001797 // Add a throw route for the VPN server endpoint, if one was specified.
1798 String endpoint = parameters[5];
1799 if (!endpoint.isEmpty()) {
1800 try {
1801 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1802 if (addr instanceof Inet4Address) {
1803 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1804 } else if (addr instanceof Inet6Address) {
1805 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1806 } else {
1807 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1808 }
1809 } catch (IllegalArgumentException e) {
1810 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1811 }
1812 }
1813
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001814 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001815 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001816 // Set the start time
1817 mConfig.startTime = SystemClock.elapsedRealtime();
1818
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001819 // Check if the thread is interrupted while we are waiting.
1820 checkpoint(false);
1821
Chia-chi Yehe9107902011-07-02 01:48:50 -07001822 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001823 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001824 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001825 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001826
1827 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001828 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01001829 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001830
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001831 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001832
1833 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001834 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001835 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001836 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001837 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001838 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001839 }
1840 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001841
1842 /**
1843 * Monitor the daemons we started, moving to disconnected state if the
1844 * underlying services fail.
1845 */
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001846 private void monitorDaemons() throws InterruptedException{
Jeff Sharkey899223b2012-08-04 15:24:58 -07001847 if (!mNetworkInfo.isConnected()) {
1848 return;
1849 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001850 while (true) {
1851 Thread.sleep(2000);
1852 for (int i = 0; i < mDaemons.length; i++) {
1853 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1854 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001855 }
1856 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001857 }
1858 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001859 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001860}