blob: a5876ddda745cd464cedf00ce8d772de6a40f9b6 [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 Makb31b8332016-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 Makb31b8332016-06-30 11:19:20 +010081import com.android.internal.R;
Chad Brubakerc2865192013-07-10 14:46:23 -070082import com.android.internal.annotations.GuardedBy;
Robin Lee4d03abc2016-05-09 12:32:27 +010083import com.android.internal.annotations.VisibleForTesting;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070084import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070085import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080086import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070088import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070089
Jeff Davidson05542602014-08-11 14:07:27 -070090import libcore.io.IoUtils;
91
Chia-chi Yeh97a61562011-07-14 15:05:05 -070092import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070093import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070094import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070095import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070097import java.net.Inet6Address;
98import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070099import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700101import java.util.Arrays;
Robin Lee4d03abc2016-05-09 12:32:27 +0100102import java.util.Collection;
103import java.util.Collections;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104import java.util.List;
Robin Lee4d03abc2016-05-09 12:32:27 +0100105import java.util.Set;
Paul Jensen0784eea2014-08-19 16:00:24 -0400106import java.util.SortedSet;
107import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700108import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700109
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700110/**
111 * @hide
112 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400113public class Vpn {
114 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700115 private static final String TAG = "Vpn";
116 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117
Jeff Sharkey899223b2012-08-04 15:24:58 -0700118 // TODO: create separate trackers for each unique VPN to support
119 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700120
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400121 private Context mContext;
122 private NetworkInfo mNetworkInfo;
123 private String mPackage;
124 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700125 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700126 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700127 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700128 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700129 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400130 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700131 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132 private NetworkAgent mNetworkAgent;
133 private final Looper mLooper;
134 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700135
Robin Lee4d03abc2016-05-09 12:32:27 +0100136 /**
Robin Lee17e61832016-05-09 13:46:28 +0100137 * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
138 * only applies to {@link VpnService} connections.
139 */
140 private boolean mAlwaysOn = false;
141
142 /**
143 * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
144 * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
145 * not set.
146 */
147 private boolean mLockdown = false;
148
149 /**
Robin Lee4d03abc2016-05-09 12:32:27 +0100150 * List of UIDs that are set to use this VPN by default. Normally, every UID in the user is
151 * added to this set but that can be changed by adding allowed or disallowed applications. It
152 * is non-null iff the VPN is connected.
153 *
154 * Unless the VPN has set allowBypass=true, these UIDs are forced into the VPN.
155 *
156 * @see VpnService.Builder#addAllowedApplication(String)
157 * @see VpnService.Builder#addDisallowedApplication(String)
158 */
Chad Brubakerc2865192013-07-10 14:46:23 -0700159 @GuardedBy("this")
Robin Lee4d03abc2016-05-09 12:32:27 +0100160 private Set<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700161
Robin Lee17e61832016-05-09 13:46:28 +0100162 /**
163 * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
164 * when VPN is not running. For example, during system startup or after a crash.
165 * @see mLockdown
166 */
167 @GuardedBy("this")
168 private Set<UidRange> mBlockedUsers = new ArraySet<>();
169
Paul Jensen0784eea2014-08-19 16:00:24 -0400170 // Handle of user initiating VPN.
171 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700172
Robin Lee812800c2016-05-13 15:38:08 +0100173 // Listen to package remove and change event in this user
174 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
175 @Override
176 public void onReceive(Context context, Intent intent) {
177 final Uri data = intent.getData();
178 final String packageName = data == null ? null : data.getSchemeSpecificPart();
179 if (packageName == null) {
180 return;
181 }
182
183 synchronized (Vpn.this) {
184 // Avoid race that always-on package has been unset
185 if (!packageName.equals(getAlwaysOnPackage())) {
186 return;
187 }
188
189 final String action = intent.getAction();
190 Log.i(TAG, "Received broadcast " + action + " for always-on package " + packageName
191 + " in user " + mUserHandle);
192
193 switch(action) {
194 case Intent.ACTION_PACKAGE_REPLACED:
195 // Start vpn after app upgrade
196 startAlwaysOnVpn();
197 break;
198 case Intent.ACTION_PACKAGE_REMOVED:
199 final boolean isPackageRemoved = !intent.getBooleanExtra(
200 Intent.EXTRA_REPLACING, false);
201 if (isPackageRemoved) {
202 setAndSaveAlwaysOnPackage(null, false);
203 }
204 break;
205 }
206 }
207 }
208 };
209
210 private boolean mIsPackageIntentReceiverRegistered = false;
211
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400212 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400213 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700214 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400215 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400216 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400217 mLooper = looper;
218
219 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400220 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700221
222 try {
223 netService.registerObserver(mObserver);
224 } catch (RemoteException e) {
225 Log.wtf(TAG, "Problem registering observer", e);
226 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400227
228 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
229 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
230 mNetworkCapabilities = new NetworkCapabilities();
231 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
232 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700233 }
234
Jeff Sharkey57666932013-04-30 17:01:57 -0700235 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700236 * Set if this object is responsible for watching for {@link NetworkInfo}
237 * teardown. When {@code false}, teardown is handled externally by someone
238 * else.
239 */
240 public void setEnableTeardown(boolean enableTeardown) {
241 mEnableTeardown = enableTeardown;
242 }
243
Jeff Sharkey899223b2012-08-04 15:24:58 -0700244 /**
245 * Update current state, dispaching event to listeners.
246 */
Tony Makb31b8332016-06-30 11:19:20 +0100247 @VisibleForTesting
248 protected void updateState(DetailedState detailedState, String reason) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700249 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
250 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400251 if (mNetworkAgent != null) {
252 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
253 }
Tony Makb31b8332016-06-30 11:19:20 +0100254 updateAlwaysOnNotification(detailedState);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700255 }
256
257 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000258 * Configures an always-on VPN connection through a specific application.
259 * This connection is automatically granted and persisted after a reboot.
260 *
261 * <p>The designated package should exist and declare a {@link VpnService} in its
262 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
263 * otherwise the call will fail.
264 *
Robin Lee17e61832016-05-09 13:46:28 +0100265 * @param packageName the package to designate as always-on VPN supplier.
266 * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
Robin Lee9ff1a582016-06-10 16:41:10 +0100267 * @return {@code true} if the package has been set as always-on, {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +0000268 */
Robin Lee17e61832016-05-09 13:46:28 +0100269 public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +0000270 enforceControlPermissionOrInternalCaller();
Robin Lee9ff1a582016-06-10 16:41:10 +0100271 if (VpnConfig.LEGACY_VPN.equals(packageName)) {
272 Log.w(TAG, "Not setting legacy VPN \"" + packageName + "\" as always-on.");
273 return false;
274 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000275
Robin Lee244ce8e2016-01-05 18:03:46 +0000276 if (packageName != null) {
Robin Lee9ff1a582016-06-10 16:41:10 +0100277 // Pre-authorize new always-on VPN package.
Robin Lee244ce8e2016-01-05 18:03:46 +0000278 if (!setPackageAuthorization(packageName, true)) {
279 return false;
280 }
Robin Lee9ff1a582016-06-10 16:41:10 +0100281 mAlwaysOn = true;
282 } else {
283 packageName = VpnConfig.LEGACY_VPN;
284 mAlwaysOn = false;
Robin Lee244ce8e2016-01-05 18:03:46 +0000285 }
286
Robin Lee17e61832016-05-09 13:46:28 +0100287 mLockdown = (mAlwaysOn && lockdown);
Tony Makb31b8332016-06-30 11:19:20 +0100288 if (isCurrentPreparedPackage(packageName)) {
289 updateAlwaysOnNotification(mNetworkInfo.getDetailedState());
290 } else {
291 // Prepare this app. The notification will update as a side-effect of updateState().
Robin Lee9ff1a582016-06-10 16:41:10 +0100292 prepareInternal(packageName);
293 }
Robin Lee812800c2016-05-13 15:38:08 +0100294 maybeRegisterPackageChangeReceiverLocked(packageName);
Robin Lee17e61832016-05-09 13:46:28 +0100295 setVpnForcedLocked(mLockdown);
Robin Lee244ce8e2016-01-05 18:03:46 +0000296 return true;
297 }
298
Robin Lee9ff1a582016-06-10 16:41:10 +0100299 private static boolean isNullOrLegacyVpn(String packageName) {
300 return packageName == null || VpnConfig.LEGACY_VPN.equals(packageName);
301 }
302
Robin Lee812800c2016-05-13 15:38:08 +0100303 private void unregisterPackageChangeReceiverLocked() {
304 // register previous intent filter
305 if (mIsPackageIntentReceiverRegistered) {
306 mContext.unregisterReceiver(mPackageIntentReceiver);
307 mIsPackageIntentReceiverRegistered = false;
308 }
309 }
310
311 private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
312 // Unregister IntentFilter listening for previous always-on package change
313 unregisterPackageChangeReceiverLocked();
314
Robin Lee9ff1a582016-06-10 16:41:10 +0100315 if (!isNullOrLegacyVpn(packageName)) {
Robin Lee812800c2016-05-13 15:38:08 +0100316 mIsPackageIntentReceiverRegistered = true;
317
318 IntentFilter intentFilter = new IntentFilter();
319 // Protected intent can only be sent by system. No permission required in register.
320 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
321 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 intentFilter.addDataScheme("package");
323 intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
324 mContext.registerReceiverAsUser(
325 mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
326 }
327 }
328
Robin Lee244ce8e2016-01-05 18:03:46 +0000329 /**
330 * @return the package name of the VPN controller responsible for always-on VPN,
331 * or {@code null} if none is set or always-on VPN is controlled through
332 * lockdown instead.
333 * @hide
334 */
335 public synchronized String getAlwaysOnPackage() {
336 enforceControlPermissionOrInternalCaller();
Robin Lee17e61832016-05-09 13:46:28 +0100337 return (mAlwaysOn ? mPackage : null);
Robin Lee244ce8e2016-01-05 18:03:46 +0000338 }
339
340 /**
Robin Lee812800c2016-05-13 15:38:08 +0100341 * Save the always-on package and lockdown config into Settings.Secure
342 */
343 public synchronized void saveAlwaysOnPackage() {
344 final long token = Binder.clearCallingIdentity();
345 try {
346 final ContentResolver cr = mContext.getContentResolver();
347 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
348 getAlwaysOnPackage(), mUserHandle);
349 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
350 (mLockdown ? 1 : 0), mUserHandle);
351 } finally {
352 Binder.restoreCallingIdentity(token);
353 }
354 }
355
356 /**
357 * Set and save always-on package and lockdown config
358 * @see Vpn#setAlwaysOnPackage(String, boolean)
359 * @see Vpn#saveAlwaysOnPackage()
360 *
361 * @return result of Vpn#setAndSaveAlwaysOnPackage(String, boolean)
362 */
363 private synchronized boolean setAndSaveAlwaysOnPackage(String packageName, boolean lockdown) {
364 if (setAlwaysOnPackage(packageName, lockdown)) {
365 saveAlwaysOnPackage();
366 return true;
367 } else {
368 return false;
369 }
370 }
371
372 /**
373 * @return {@code true} if the service was started, the service was already connected, or there
374 * was no always-on VPN to start. {@code false} otherwise.
375 */
376 public boolean startAlwaysOnVpn() {
377 final String alwaysOnPackage;
378 synchronized (this) {
379 alwaysOnPackage = getAlwaysOnPackage();
380 // Skip if there is no service to start.
381 if (alwaysOnPackage == null) {
382 return true;
383 }
384 // Skip if the service is already established. This isn't bulletproof: it's not bound
385 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
386 // which may restart the connection.
387 if (getNetworkInfo().isConnected()) {
388 return true;
389 }
390 }
391
392 // Start the VPN service declared in the app's manifest.
393 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
394 serviceIntent.setPackage(alwaysOnPackage);
395 try {
396 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
397 } catch (RuntimeException e) {
398 Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
399 return false;
400 }
401 }
402
403 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700404 * Prepare for a VPN application. This method is designed to solve
405 * race conditions. It first compares the current prepared package
406 * with {@code oldPackage}. If they are the same, the prepared
407 * package is revoked and replaced with {@code newPackage}. If
408 * {@code oldPackage} is {@code null}, the comparison is omitted.
409 * If {@code newPackage} is the same package or {@code null}, the
410 * revocation is omitted. This method returns {@code true} if the
411 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700412 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700413 * Legacy VPN is handled specially since it is not a real package.
414 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
415 * it can be revoked by itself.
416 *
Victor Chang98a633a2016-05-27 17:30:49 +0100417 * Note: when we added VPN pre-consent in http://ag/522961 the names oldPackage
418 * and newPackage become misleading, because when an app is pre-consented, we
419 * actually prepare oldPackage, not newPackage.
420 *
421 * Their meanings actually are:
422 *
423 * - oldPackage non-null, newPackage null: App calling VpnService#prepare().
424 * - oldPackage null, newPackage non-null: ConfirmDialog calling prepareVpn().
Robin Lee812800c2016-05-13 15:38:08 +0100425 * - oldPackage null, newPackage=LEGACY_VPN: Used internally to disconnect
Victor Chang98a633a2016-05-27 17:30:49 +0100426 * and revoke any current app VPN and re-prepare legacy vpn.
427 *
Robin Lee812800c2016-05-13 15:38:08 +0100428 * TODO: Rename the variables - or split this method into two - and end this confusion.
429 * TODO: b/29032008 Migrate code from prepare(oldPackage=non-null, newPackage=LEGACY_VPN)
430 * to prepare(oldPackage=null, newPackage=LEGACY_VPN)
Victor Chang98a633a2016-05-27 17:30:49 +0100431 *
432 * @param oldPackage The package name of the old VPN application
433 * @param newPackage The package name of the new VPN application
434 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700435 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700436 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700437 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700438 if (oldPackage != null) {
Victor Chang98a633a2016-05-27 17:30:49 +0100439 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100440 if (mAlwaysOn && !isCurrentPreparedPackage(oldPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100441 return false;
442 }
443
444 // Package is not same or old package was reinstalled.
445 if (!isCurrentPreparedPackage(oldPackage)) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700446 // The package doesn't match. We return false (to obtain user consent) unless the
447 // user has already consented to that VPN package.
448 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
449 prepareInternal(oldPackage);
450 return true;
451 }
452 return false;
453 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
454 && !isVpnUserPreConsented(oldPackage)) {
455 // Currently prepared VPN is revoked, so unprepare it and return false.
456 prepareInternal(VpnConfig.LEGACY_VPN);
457 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700458 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700459 }
460
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700461 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700462 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
Victor Chang98a633a2016-05-27 17:30:49 +0100463 isCurrentPreparedPackage(newPackage))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700464 return true;
465 }
466
Robin Lee1b1bcd72016-02-12 18:11:30 +0000467 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700468 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700469
Victor Chang98a633a2016-05-27 17:30:49 +0100470 // Stop an existing always-on VPN from being dethroned by other apps.
Robin Lee812800c2016-05-13 15:38:08 +0100471 if (mAlwaysOn && !isCurrentPreparedPackage(newPackage)) {
Victor Chang98a633a2016-05-27 17:30:49 +0100472 return false;
473 }
474
Jeff Davidson11008a72014-11-20 13:12:46 -0800475 prepareInternal(newPackage);
476 return true;
477 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700478
Victor Chang98a633a2016-05-27 17:30:49 +0100479 private boolean isCurrentPreparedPackage(String packageName) {
480 // We can't just check that packageName matches mPackage, because if the app was uninstalled
481 // and reinstalled it will no longer be prepared. Instead check the UID.
482 return getAppUid(packageName, mUserHandle) == mOwnerUID;
483 }
484
Jeff Davidson11008a72014-11-20 13:12:46 -0800485 /** Prepare the VPN for the given package. Does not perform permission checks. */
486 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400487 long token = Binder.clearCallingIdentity();
488 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800489 // Reset the interface.
490 if (mInterface != null) {
491 mStatusIntent = null;
492 agentDisconnect();
493 jniReset(mInterface);
494 mInterface = null;
495 mVpnUsers = null;
496 }
497
498 // Revoke the connection or stop LegacyVpnRunner.
499 if (mConnection != null) {
500 try {
501 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
502 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
503 } catch (Exception e) {
504 // ignore
505 }
506 mContext.unbindService(mConnection);
507 mConnection = null;
508 } else if (mLegacyVpnRunner != null) {
509 mLegacyVpnRunner.exit();
510 mLegacyVpnRunner = null;
511 }
512
513 try {
514 mNetd.denyProtect(mOwnerUID);
515 } catch (Exception e) {
516 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
517 }
518
519 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
520 mPackage = newPackage;
521 mOwnerUID = getAppUid(newPackage, mUserHandle);
522 try {
523 mNetd.allowProtect(mOwnerUID);
524 } catch (Exception e) {
525 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
526 }
527 mConfig = null;
528
529 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400530 } finally {
531 Binder.restoreCallingIdentity(token);
532 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700533 }
534
Jeff Davidson05542602014-08-11 14:07:27 -0700535 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100536 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700537 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000538 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700539 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000540 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700541
Robin Lee3b3dd942015-05-12 18:14:58 +0100542 int uid = getAppUid(packageName, mUserHandle);
543 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
544 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000545 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700546 }
547
548 long token = Binder.clearCallingIdentity();
549 try {
550 AppOpsManager appOps =
551 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100552 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700553 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000554 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700555 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100556 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700557 } finally {
558 Binder.restoreCallingIdentity(token);
559 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000560 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700561 }
562
563 private boolean isVpnUserPreConsented(String packageName) {
564 AppOpsManager appOps =
565 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
566
567 // Verify that the caller matches the given package and has permission to activate VPNs.
568 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
569 packageName) == AppOpsManager.MODE_ALLOWED;
570 }
571
Paul Jensen0784eea2014-08-19 16:00:24 -0400572 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700573 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400574 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700575 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400576 PackageManager pm = mContext.getPackageManager();
577 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700578 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700579 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400580 } catch (NameNotFoundException e) {
581 result = -1;
582 }
583 return result;
584 }
585
586 public NetworkInfo getNetworkInfo() {
587 return mNetworkInfo;
588 }
589
Paul Jensen31a94f42015-02-13 14:18:39 -0500590 public int getNetId() {
591 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
592 }
593
Lorenzo Colitti60446162014-09-20 00:14:31 +0900594 private LinkProperties makeLinkProperties() {
595 boolean allowIPv4 = mConfig.allowIPv4;
596 boolean allowIPv6 = mConfig.allowIPv6;
597
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400598 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900599
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400600 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700601
Lorenzo Colitti60446162014-09-20 00:14:31 +0900602 if (mConfig.addresses != null) {
603 for (LinkAddress address : mConfig.addresses) {
604 lp.addLinkAddress(address);
605 allowIPv4 |= address.getAddress() instanceof Inet4Address;
606 allowIPv6 |= address.getAddress() instanceof Inet6Address;
607 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400608 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900609
610 if (mConfig.routes != null) {
611 for (RouteInfo route : mConfig.routes) {
612 lp.addRoute(route);
613 InetAddress address = route.getDestination().getAddress();
614 allowIPv4 |= address instanceof Inet4Address;
615 allowIPv6 |= address instanceof Inet6Address;
616 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400617 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700618
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400619 if (mConfig.dnsServers != null) {
620 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700621 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
622 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900623 allowIPv4 |= address instanceof Inet4Address;
624 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400625 }
626 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700627
Lorenzo Colitti60446162014-09-20 00:14:31 +0900628 if (!allowIPv4) {
629 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
630 }
631 if (!allowIPv6) {
632 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
633 }
634
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400635 // Concatenate search domains into a string.
636 StringBuilder buffer = new StringBuilder();
637 if (mConfig.searchDomains != null) {
638 for (String domain : mConfig.searchDomains) {
639 buffer.append(domain).append(' ');
640 }
641 }
642 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700643
Lorenzo Colitti60446162014-09-20 00:14:31 +0900644 // TODO: Stop setting the MTU in jniCreate and set it here.
645
646 return lp;
647 }
648
649 private void agentConnect() {
650 LinkProperties lp = makeLinkProperties();
651
652 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
653 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
654 } else {
655 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
656 }
657
Robin Lee323f29d2016-05-04 16:38:06 +0100658 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700659
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700660 NetworkMisc networkMisc = new NetworkMisc();
Robin Lee17e61832016-05-09 13:46:28 +0100661 networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700662
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400663 long token = Binder.clearCallingIdentity();
664 try {
665 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700666 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700667 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400668 public void unwanted() {
669 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700670 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400671 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700672 } finally {
673 Binder.restoreCallingIdentity(token);
674 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700675
Robin Lee4d03abc2016-05-09 12:32:27 +0100676 mVpnUsers = createUserAndRestrictedProfilesRanges(mUserHandle,
677 mConfig.allowedApplications, mConfig.disallowedApplications);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400678 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
Robin Lee323f29d2016-05-04 16:38:06 +0100679
680 mNetworkInfo.setIsAvailable(true);
681 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400682 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700683
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700684 private boolean canHaveRestrictedProfile(int userId) {
685 long token = Binder.clearCallingIdentity();
686 try {
687 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
688 } finally {
689 Binder.restoreCallingIdentity(token);
690 }
691 }
692
Tony Makb31b8332016-06-30 11:19:20 +0100693 private void agentDisconnect(NetworkAgent networkAgent) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400694 if (networkAgent != null) {
Tony Makb31b8332016-06-30 11:19:20 +0100695 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
696 networkInfo.setIsAvailable(false);
697 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400698 networkAgent.sendNetworkInfo(networkInfo);
699 }
700 }
701
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400702 private void agentDisconnect() {
703 if (mNetworkInfo.isConnected()) {
Tony Makb31b8332016-06-30 11:19:20 +0100704 mNetworkInfo.setIsAvailable(false);
705 updateState(DetailedState.DISCONNECTED, "agentDisconnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400706 mNetworkAgent = null;
707 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700708 }
709
710 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700711 * Establish a VPN network and return the file descriptor of the VPN
712 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700713 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700714 *
715 * @param config The parameters to configure the network.
716 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700717 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700718 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700719 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700720 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400721 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700722 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700723 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700724 // Check to ensure consent hasn't been revoked since we were prepared.
725 if (!isVpnUserPreConsented(mPackage)) {
726 return null;
727 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700728 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700729 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
730 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700731 long token = Binder.clearCallingIdentity();
732 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700733 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400734 UserInfo user = mgr.getUserInfo(mUserHandle);
Robin Lee628ae0d2016-05-20 14:53:48 +0100735 if (user.isRestricted()) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700736 throw new SecurityException("Restricted users cannot establish VPNs");
737 }
738
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700739 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400740 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700741 if (info == null) {
742 throw new SecurityException("Cannot find " + config.user);
743 }
744 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
745 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
746 }
747 } catch (RemoteException e) {
748 throw new SecurityException("Cannot find " + config.user);
749 } finally {
750 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700751 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700752
Chad Brubaker850eb672014-03-21 21:02:47 +0000753 // Save the old config in case we need to go back.
754 VpnConfig oldConfig = mConfig;
755 String oldInterface = mInterface;
756 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400757 NetworkAgent oldNetworkAgent = mNetworkAgent;
758 mNetworkAgent = null;
Robin Lee4d03abc2016-05-09 12:32:27 +0100759 Set<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000760
Chia-chi Yehe9107902011-07-02 01:48:50 -0700761 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700762 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700763 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700764 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700765 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700766
Chad Brubakerc2865192013-07-10 14:46:23 -0700767 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700768 StringBuilder builder = new StringBuilder();
769 for (LinkAddress address : config.addresses) {
770 builder.append(" " + address);
771 }
772 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700773 throw new IllegalArgumentException("At least one address must be specified");
774 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700775 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700776 if (!mContext.bindServiceAsUser(intent, connection,
777 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
778 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700779 throw new IllegalStateException("Cannot bind " + config.user);
780 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000781
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700782 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700783 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700784
785 // Fill more values.
786 config.user = mPackage;
787 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700788 config.startTime = SystemClock.elapsedRealtime();
789 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000790
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700791 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400792 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000793
794 if (oldConnection != null) {
795 mContext.unbindService(oldConnection);
796 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400797 // Remove the old tun's user forwarding rules
798 // The new tun's user rules have already been added so they will take over
799 // as rules are deleted. This prevents data leakage as the rules are moved over.
800 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000801 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000802 jniReset(oldInterface);
803 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700804
805 try {
806 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
807 } catch (IOException e) {
808 throw new IllegalStateException(
809 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
810 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000811 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000812 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400813 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000814 // restore old state
815 mConfig = oldConfig;
816 mConnection = oldConnection;
817 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400818 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000819 mInterface = oldInterface;
820 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700821 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000822 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700823 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700824 }
825
Chad Brubakerc2865192013-07-10 14:46:23 -0700826 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800827 return mNetworkAgent != null && mInterface != null;
828 }
829
830 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
831 // that a call to mutate VPN state is admissible.
832 private boolean isCallerEstablishedOwnerLocked() {
833 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700834 }
835
Paul Jensen0784eea2014-08-19 16:00:24 -0400836 // Note: Return type guarantees results are deduped and sorted, which callers require.
837 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
838 SortedSet<Integer> uids = new TreeSet<Integer>();
839 for (String app : packageNames) {
840 int uid = getAppUid(app, userHandle);
841 if (uid != -1) uids.add(uid);
842 }
843 return uids;
844 }
845
Robin Lee4d03abc2016-05-09 12:32:27 +0100846 /**
847 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
848 * associated with one user, and any restricted profiles attached to that user.
849 *
850 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
851 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
852 * in each user and profile will be included.
853 *
854 * @param userHandle The userId to create UID ranges for along with any of its restricted
855 * profiles.
856 * @param allowedApplications (optional) whitelist of applications to include.
857 * @param disallowedApplications (optional) blacklist of applications to exclude.
858 */
859 @VisibleForTesting
860 Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
861 @Nullable List<String> allowedApplications,
862 @Nullable List<String> disallowedApplications) {
863 final Set<UidRange> ranges = new ArraySet<>();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700864
Robin Lee4d03abc2016-05-09 12:32:27 +0100865 // Assign the top-level user to the set of ranges
866 addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
867
868 // If the user can have restricted profiles, assign all its restricted profiles too
869 if (canHaveRestrictedProfile(userHandle)) {
870 final long token = Binder.clearCallingIdentity();
871 List<UserInfo> users;
872 try {
Robin Lee17e61832016-05-09 13:46:28 +0100873 users = UserManager.get(mContext).getUsers(true);
Robin Lee4d03abc2016-05-09 12:32:27 +0100874 } finally {
875 Binder.restoreCallingIdentity(token);
876 }
877 for (UserInfo user : users) {
878 if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
879 addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
880 }
881 }
882 }
883 return ranges;
884 }
885
886 /**
887 * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
888 * associated with one user.
889 *
890 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
891 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
892 * in the user will be included.
893 *
894 * @param ranges {@link Set} of {@link UidRange}s to which to add.
895 * @param userHandle The userId to add to {@param ranges}.
896 * @param allowedApplications (optional) whitelist of applications to include.
897 * @param disallowedApplications (optional) blacklist of applications to exclude.
898 */
899 @VisibleForTesting
900 void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
901 @Nullable List<String> allowedApplications,
902 @Nullable List<String> disallowedApplications) {
903 if (allowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400904 // Add ranges covering all UIDs for allowedApplications.
905 int start = -1, stop = -1;
Robin Lee4d03abc2016-05-09 12:32:27 +0100906 for (int uid : getAppsUids(allowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400907 if (start == -1) {
908 start = uid;
909 } else if (uid != stop + 1) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100910 ranges.add(new UidRange(start, stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400911 start = uid;
912 }
913 stop = uid;
914 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100915 if (start != -1) ranges.add(new UidRange(start, stop));
916 } else if (disallowedApplications != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400917 // Add all ranges for user skipping UIDs for disallowedApplications.
918 final UidRange userRange = UidRange.createForUser(userHandle);
919 int start = userRange.start;
Robin Lee4d03abc2016-05-09 12:32:27 +0100920 for (int uid : getAppsUids(disallowedApplications, userHandle)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400921 if (uid == start) {
922 start++;
923 } else {
Robin Lee4d03abc2016-05-09 12:32:27 +0100924 ranges.add(new UidRange(start, uid - 1));
Paul Jensen0784eea2014-08-19 16:00:24 -0400925 start = uid + 1;
926 }
927 }
Robin Lee4d03abc2016-05-09 12:32:27 +0100928 if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
Paul Jensen0784eea2014-08-19 16:00:24 -0400929 } else {
930 // Add all UIDs for the user.
Robin Lee4d03abc2016-05-09 12:32:27 +0100931 ranges.add(UidRange.createForUser(userHandle));
Paul Jensen0784eea2014-08-19 16:00:24 -0400932 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700933 }
934
Paul Jensen0784eea2014-08-19 16:00:24 -0400935 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
936 // apply to userHandle.
937 private List<UidRange> uidRangesForUser(int userHandle) {
938 final UidRange userRange = UidRange.createForUser(userHandle);
939 final List<UidRange> ranges = new ArrayList<UidRange>();
940 for (UidRange range : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +0100941 if (userRange.containsRange(range)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400942 ranges.add(range);
943 }
944 }
945 return ranges;
946 }
947
948 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800949 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700950 throw new IllegalStateException("VPN is not active");
951 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400952 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700953 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400954 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700955 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400956 mVpnUsers.removeAll(ranges);
Chad Brubakerc2865192013-07-10 14:46:23 -0700957 }
958
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700959 public void onUserAdded(int userHandle) {
960 // If the user is restricted tie them to the parent user's VPN
961 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100962 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700963 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100964 if (mVpnUsers != null) {
965 try {
966 addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
967 mConfig.disallowedApplications);
968 if (mNetworkAgent != null) {
969 final List<UidRange> ranges = uidRangesForUser(userHandle);
970 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
971 }
972 } catch (Exception e) {
973 Log.wtf(TAG, "Failed to add restricted user to owner", e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400974 }
Robin Lee17e61832016-05-09 13:46:28 +0100975 }
976 if (mAlwaysOn) {
977 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700978 }
979 }
980 }
981 }
982
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700983 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700984 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700985 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Robin Lee17e61832016-05-09 13:46:28 +0100986 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700987 synchronized(Vpn.this) {
Robin Lee17e61832016-05-09 13:46:28 +0100988 if (mVpnUsers != null) {
989 try {
990 removeVpnUserLocked(userHandle);
991 } catch (Exception e) {
992 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
993 }
994 }
995 if (mAlwaysOn) {
996 setVpnForcedLocked(mLockdown);
Chad Brubakerc2865192013-07-10 14:46:23 -0700997 }
998 }
999 }
1000 }
1001
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001002 /**
Robin Lee17e61832016-05-09 13:46:28 +01001003 * Called when the user associated with this VPN has just been stopped.
1004 */
1005 public synchronized void onUserStopped() {
1006 // Switch off networking lockdown (if it was enabled)
1007 setVpnForcedLocked(false);
1008 mAlwaysOn = false;
1009
Robin Lee812800c2016-05-13 15:38:08 +01001010 unregisterPackageChangeReceiverLocked();
Robin Lee17e61832016-05-09 13:46:28 +01001011 // Quit any active connections
1012 agentDisconnect();
1013 }
1014
1015 /**
1016 * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
1017 * service app itself, to only sockets that have had {@code protect()} called on them. All
1018 * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
1019 *
1020 * The exception for the VPN UID isn't technically necessary -- setup should use protected
1021 * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
1022 *
1023 * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
1024 * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
1025 *
1026 * @param enforce {@code true} to require that all traffic under the jurisdiction of this
1027 * {@link Vpn} goes through a VPN connection or is blocked until one is
1028 * available, {@code false} to lift the requirement.
1029 *
1030 * @see #mBlockedUsers
1031 */
1032 @GuardedBy("this")
1033 private void setVpnForcedLocked(boolean enforce) {
1034 final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
1035 if (enforce) {
1036 final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
1037 /* allowedApplications */ null,
1038 /* disallowedApplications */ Collections.singletonList(mPackage));
1039
1040 removedRanges.removeAll(addedRanges);
1041 addedRanges.removeAll(mBlockedUsers);
1042
1043 setAllowOnlyVpnForUids(false, removedRanges);
1044 setAllowOnlyVpnForUids(true, addedRanges);
1045 } else {
1046 setAllowOnlyVpnForUids(false, removedRanges);
1047 }
1048 }
1049
1050 /**
1051 * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
1052 * to make connections through sockets that have had {@code protect()} called on them.
1053 *
1054 * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
1055 * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
1056 * {@code true}) or to remove.
1057 * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
1058 * including added ranges that already existed or removed ones that didn't.
1059 */
1060 @GuardedBy("this")
1061 private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
1062 if (ranges.size() == 0) {
1063 return true;
1064 }
1065 final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
1066 try {
1067 mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
1068 } catch (RemoteException | RuntimeException e) {
1069 Log.e(TAG, "Updating blocked=" + enforce
1070 + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
1071 return false;
1072 }
1073 if (enforce) {
1074 mBlockedUsers.addAll(ranges);
1075 } else {
1076 mBlockedUsers.removeAll(ranges);
1077 }
1078 return true;
1079 }
1080
1081 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07001082 * Return the configuration of the currently running VPN.
1083 */
1084 public VpnConfig getVpnConfig() {
1085 enforceControlPermission();
1086 return mConfig;
1087 }
1088
Jeff Sharkey899223b2012-08-04 15:24:58 -07001089 @Deprecated
1090 public synchronized void interfaceStatusChanged(String iface, boolean up) {
1091 try {
1092 mObserver.interfaceStatusChanged(iface, up);
1093 } catch (RemoteException e) {
1094 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001095 }
1096 }
1097
Jeff Sharkey899223b2012-08-04 15:24:58 -07001098 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
1099 @Override
1100 public void interfaceStatusChanged(String interfaze, boolean up) {
1101 synchronized (Vpn.this) {
1102 if (!up && mLegacyVpnRunner != null) {
1103 mLegacyVpnRunner.check(interfaze);
1104 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001105 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001106 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001107
Jeff Sharkey899223b2012-08-04 15:24:58 -07001108 @Override
1109 public void interfaceRemoved(String interfaze) {
1110 synchronized (Vpn.this) {
1111 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001112 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001113 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -05001114 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001115 mInterface = null;
1116 if (mConnection != null) {
1117 mContext.unbindService(mConnection);
1118 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001119 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001120 } else if (mLegacyVpnRunner != null) {
1121 mLegacyVpnRunner.exit();
1122 mLegacyVpnRunner = null;
1123 }
1124 }
1125 }
1126 }
1127 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001128
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001129 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -08001130 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001131 }
1132
Robin Lee244ce8e2016-01-05 18:03:46 +00001133 private void enforceControlPermissionOrInternalCaller() {
1134 // Require caller to be either an application with CONTROL_VPN permission or a process
1135 // in the system server.
1136 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
1137 "Unauthorized Caller");
1138 }
1139
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001140 private class Connection implements ServiceConnection {
1141 private IBinder mService;
1142
1143 @Override
1144 public void onServiceConnected(ComponentName name, IBinder service) {
1145 mService = service;
1146 }
1147
1148 @Override
1149 public void onServiceDisconnected(ComponentName name) {
1150 mService = null;
1151 }
1152 }
1153
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001154 private void prepareStatusIntent() {
1155 final long token = Binder.clearCallingIdentity();
1156 try {
1157 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
1158 } finally {
1159 Binder.restoreCallingIdentity(token);
1160 }
1161 }
1162
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001163 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001164 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001165 return false;
1166 }
1167 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001168 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001169 return success;
1170 }
1171
1172 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001173 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001174 return false;
1175 }
1176 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001177 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001178 return success;
1179 }
1180
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001181 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1182 if (!isCallerEstablishedOwnerLocked()) {
1183 return false;
1184 }
1185 if (networks == null) {
1186 mConfig.underlyingNetworks = null;
1187 } else {
1188 mConfig.underlyingNetworks = new Network[networks.length];
1189 for (int i = 0; i < networks.length; ++i) {
1190 if (networks[i] == null) {
1191 mConfig.underlyingNetworks[i] = null;
1192 } else {
1193 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1194 }
1195 }
1196 }
1197 return true;
1198 }
1199
1200 public synchronized Network[] getUnderlyingNetworks() {
1201 if (!isRunningLocked()) {
1202 return null;
1203 }
1204 return mConfig.underlyingNetworks;
1205 }
1206
Wenchao Tongf5ea3402015-03-04 13:26:38 -08001207 /**
1208 * This method should only be called by ConnectivityService. Because it doesn't
1209 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1210 */
1211 public synchronized VpnInfo getVpnInfo() {
1212 if (!isRunningLocked()) {
1213 return null;
1214 }
1215
1216 VpnInfo info = new VpnInfo();
1217 info.ownerUid = mOwnerUID;
1218 info.vpnIface = mInterface;
1219 return info;
1220 }
1221
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001222 public synchronized boolean appliesToUid(int uid) {
1223 if (!isRunningLocked()) {
1224 return false;
1225 }
1226 for (UidRange uidRange : mVpnUsers) {
Robin Lee4d03abc2016-05-09 12:32:27 +01001227 if (uidRange.contains(uid)) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001228 return true;
1229 }
1230 }
1231 return false;
1232 }
1233
Robin Lee17e61832016-05-09 13:46:28 +01001234 /**
Robin Leeebbcb542016-05-24 16:35:10 +01001235 * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1236 * A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1237 * not connected, or if the VPN is connected but does not apply to the UID.
Robin Lee17e61832016-05-09 13:46:28 +01001238 *
1239 * @see #mBlockedUsers
1240 */
1241 public synchronized boolean isBlockingUid(int uid) {
Robin Leeebbcb542016-05-24 16:35:10 +01001242 if (!mLockdown) {
1243 return false;
Robin Lee17e61832016-05-09 13:46:28 +01001244 }
Robin Leeebbcb542016-05-24 16:35:10 +01001245
1246 if (mNetworkInfo.isConnected()) {
1247 return !appliesToUid(uid);
1248 } else {
1249 for (UidRange uidRange : mBlockedUsers) {
1250 if (uidRange.contains(uid)) {
1251 return true;
1252 }
1253 }
1254 return false;
1255 }
Robin Lee17e61832016-05-09 13:46:28 +01001256 }
1257
Tony Makb31b8332016-06-30 11:19:20 +01001258 private void updateAlwaysOnNotification(DetailedState networkState) {
1259 final boolean visible = (mAlwaysOn && networkState != DetailedState.CONNECTED);
1260 updateAlwaysOnNotificationInternal(visible);
1261 }
1262
1263 @VisibleForTesting
1264 protected void updateAlwaysOnNotificationInternal(boolean visible) {
1265 final UserHandle user = UserHandle.of(mUserHandle);
1266 final long token = Binder.clearCallingIdentity();
1267 try {
1268 final NotificationManager notificationManager = NotificationManager.from(mContext);
1269 if (!visible) {
1270 notificationManager.cancelAsUser(TAG, 0, user);
1271 return;
1272 }
1273 final Intent intent = new Intent(Settings.ACTION_VPN_SETTINGS);
1274 final PendingIntent configIntent = PendingIntent.getActivityAsUser(
1275 mContext, /* request */ 0, intent,
1276 PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT,
1277 null, user);
1278 final Notification.Builder builder = new Notification.Builder(mContext)
1279 .setDefaults(0)
1280 .setSmallIcon(R.drawable.vpn_connected)
1281 .setContentTitle(mContext.getString(R.string.vpn_lockdown_disconnected))
1282 .setContentText(mContext.getString(R.string.vpn_lockdown_config))
1283 .setContentIntent(configIntent)
1284 .setCategory(Notification.CATEGORY_SYSTEM)
1285 .setPriority(Notification.PRIORITY_LOW)
1286 .setVisibility(Notification.VISIBILITY_PUBLIC)
1287 .setOngoing(true)
1288 .setColor(mContext.getColor(R.color.system_notification_accent_color));
1289 notificationManager.notifyAsUser(TAG, 0, builder.build(), user);
1290 } finally {
1291 Binder.restoreCallingIdentity(token);
1292 }
1293 }
1294
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001295 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001296 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001297 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001298 private native void jniReset(String interfaze);
1299 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07001300 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1301 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001302
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001303 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1304 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -07001305 // Currently legacy VPN only works on IPv4.
1306 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001307 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001308 }
1309 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001310
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001311 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -07001312 }
1313
1314 /**
1315 * Start legacy VPN, controlling native daemons as needed. Creates a
1316 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001317 *
1318 * Should only be called to respond to Binder requests as this enforces caller permission. Use
1319 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1320 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -07001321 */
1322 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001323 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001324 long token = Binder.clearCallingIdentity();
1325 try {
1326 startLegacyVpnPrivileged(profile, keyStore, egress);
1327 } finally {
1328 Binder.restoreCallingIdentity(token);
1329 }
1330 }
1331
1332 /**
1333 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1334 * permissions under the assumption that the caller is the system.
1335 *
1336 * Callers are responsible for checking permissions if needed.
1337 */
1338 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1339 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001340 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -04001341 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +00001342 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1343 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -04001344 throw new SecurityException("Restricted users cannot establish VPNs");
1345 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001346
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +09001347 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1348 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1349 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -07001350
1351 // Load certificates.
1352 String privateKey = "";
1353 String userCert = "";
1354 String caCert = "";
1355 String serverCert = "";
1356 if (!profile.ipsecUserCert.isEmpty()) {
1357 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1358 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001359 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001360 }
1361 if (!profile.ipsecCaCert.isEmpty()) {
1362 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001363 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001364 }
1365 if (!profile.ipsecServerCert.isEmpty()) {
1366 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -07001367 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001368 }
1369 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1370 throw new IllegalStateException("Cannot load credentials");
1371 }
1372
1373 // Prepare arguments for racoon.
1374 String[] racoon = null;
1375 switch (profile.type) {
1376 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1377 racoon = new String[] {
1378 iface, profile.server, "udppsk", profile.ipsecIdentifier,
1379 profile.ipsecSecret, "1701",
1380 };
1381 break;
1382 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1383 racoon = new String[] {
1384 iface, profile.server, "udprsa", privateKey, userCert,
1385 caCert, serverCert, "1701",
1386 };
1387 break;
1388 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1389 racoon = new String[] {
1390 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1391 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1392 };
1393 break;
1394 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1395 racoon = new String[] {
1396 iface, profile.server, "xauthrsa", privateKey, userCert,
1397 caCert, serverCert, profile.username, profile.password, "", gateway,
1398 };
1399 break;
1400 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1401 racoon = new String[] {
1402 iface, profile.server, "hybridrsa",
1403 caCert, serverCert, profile.username, profile.password, "", gateway,
1404 };
1405 break;
1406 }
1407
1408 // Prepare arguments for mtpd.
1409 String[] mtpd = null;
1410 switch (profile.type) {
1411 case VpnProfile.TYPE_PPTP:
1412 mtpd = new String[] {
1413 iface, "pptp", profile.server, "1723",
1414 "name", profile.username, "password", profile.password,
1415 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1416 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1417 (profile.mppe ? "+mppe" : "nomppe"),
1418 };
1419 break;
1420 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1421 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1422 mtpd = new String[] {
1423 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1424 "name", profile.username, "password", profile.password,
1425 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1426 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1427 };
1428 break;
1429 }
1430
1431 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001432 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001433 config.user = profile.key;
1434 config.interfaze = iface;
1435 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001436
1437 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001438 if (!profile.dnsServers.isEmpty()) {
1439 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1440 }
1441 if (!profile.searchDomains.isEmpty()) {
1442 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1443 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001444 startLegacyVpn(config, racoon, mtpd);
1445 }
1446
1447 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001448 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001449
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001450 // Prepare for the new request.
1451 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001452 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001453
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001454 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001455 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1456 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001457 }
1458
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001459 /** Stop legacy VPN. Permissions must be checked by callers. */
1460 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001461 if (mLegacyVpnRunner != null) {
1462 mLegacyVpnRunner.exit();
1463 mLegacyVpnRunner = null;
1464
1465 synchronized (LegacyVpnRunner.TAG) {
1466 // wait for old thread to completely finish before spinning up
1467 // new instance, otherwise state updates can be out of order.
1468 }
1469 }
1470 }
1471
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001472 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001473 * Return the information of the current ongoing legacy VPN.
1474 */
1475 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001476 // Check if the caller is authorized.
1477 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001478 return getLegacyVpnInfoPrivileged();
1479 }
1480
1481 /**
1482 * Return the information of the current ongoing legacy VPN.
1483 * Callers are responsible for checking permissions if needed.
1484 */
1485 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001486 if (mLegacyVpnRunner == null) return null;
1487
1488 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001489 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001490 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001491 if (mNetworkInfo.isConnected()) {
1492 info.intent = mStatusIntent;
1493 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001494 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001495 }
1496
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001497 public VpnConfig getLegacyVpnConfig() {
1498 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001499 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001500 } else {
1501 return null;
1502 }
1503 }
1504
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001505 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001506 * Bringing up a VPN connection takes time, and that is all this thread
1507 * does. Here we have plenty of time. The only thing we need to take
1508 * care of is responding to interruptions as soon as possible. Otherwise
1509 * requests will be piled up. This can be done in a Handler as a state
1510 * machine, but it is much easier to read in the current form.
1511 */
1512 private class LegacyVpnRunner extends Thread {
1513 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001514
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001515 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001516 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001517 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001518 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001519 private final AtomicInteger mOuterConnection =
1520 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001521
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001522 private long mTimer = -1;
1523
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001524 /**
1525 * Watch for the outer connection (passing in the constructor) going away.
1526 */
1527 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1528 @Override
1529 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001530 if (!mEnableTeardown) return;
1531
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001532 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1533 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1534 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1535 NetworkInfo info = (NetworkInfo)intent.getExtra(
1536 ConnectivityManager.EXTRA_NETWORK_INFO);
1537 if (info != null && !info.isConnectedOrConnecting()) {
1538 try {
1539 mObserver.interfaceStatusChanged(mOuterInterface, false);
1540 } catch (RemoteException e) {}
1541 }
1542 }
1543 }
1544 }
1545 };
1546
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001547 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001548 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001549 mConfig = config;
1550 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001551 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001552 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001553 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001554
1555 // This is the interface which VPN is running on,
1556 // mConfig.interfaze will change to point to OUR
1557 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001558 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001559 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001560 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001561 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001562
Paul Jensene75b9e32015-04-06 11:54:53 -04001563 if (!TextUtils.isEmpty(mOuterInterface)) {
1564 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1565 for (Network network : cm.getAllNetworks()) {
1566 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001567 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001568 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1569 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1570 }
1571 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001572 }
1573
1574 IntentFilter filter = new IntentFilter();
1575 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1576 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001577 }
1578
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001579 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001580 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001581 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1582 exit();
1583 }
1584 }
1585
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001586 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001587 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001588 interrupt();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001589 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001590 try {
1591 mContext.unregisterReceiver(mBroadcastReceiver);
1592 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001593 }
1594
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001595 @Override
1596 public void run() {
1597 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001598 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001599 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001600 Log.v(TAG, "Executing");
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001601 try {
1602 execute();
1603 monitorDaemons();
1604 interrupted(); // Clear interrupt flag if execute called exit.
1605 } catch (InterruptedException e) {
1606 } finally {
1607 for (LocalSocket socket : mSockets) {
1608 IoUtils.closeQuietly(socket);
1609 }
1610 // This sleep is necessary for racoon to successfully complete sending delete
1611 // message to server.
1612 try {
1613 Thread.sleep(50);
1614 } catch (InterruptedException e) {
1615 }
1616 for (String daemon : mDaemons) {
1617 SystemService.stop(daemon);
1618 }
1619 }
1620 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001621 }
1622 }
1623
1624 private void checkpoint(boolean yield) throws InterruptedException {
1625 long now = SystemClock.elapsedRealtime();
1626 if (mTimer == -1) {
1627 mTimer = now;
1628 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001629 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001630 Thread.sleep(yield ? 200 : 1);
1631 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001632 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001633 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001634 }
1635 }
1636
1637 private void execute() {
1638 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001639 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001640 try {
1641 // Initialize the timer.
1642 checkpoint(false);
1643
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001644 // Wait for the daemons to stop.
1645 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001646 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001647 checkpoint(true);
1648 }
1649 }
1650
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001651 // Clear the previous state.
1652 File state = new File("/data/misc/vpn/state");
1653 state.delete();
1654 if (state.exists()) {
1655 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001656 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001657 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001658 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001659
Chia-chi Yehe9107902011-07-02 01:48:50 -07001660 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001661 boolean restart = false;
1662 for (String[] arguments : mArguments) {
1663 restart = restart || (arguments != null);
1664 }
1665 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001666 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001667 return;
1668 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001669 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001670
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001671 // Start the daemon with arguments.
1672 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001673 String[] arguments = mArguments[i];
1674 if (arguments == null) {
1675 continue;
1676 }
1677
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001678 // Start the daemon.
1679 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001680 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001681
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001682 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001683 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001684 checkpoint(true);
1685 }
1686
1687 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001688 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001689 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001690 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001691
1692 // Wait for the socket to connect.
1693 while (true) {
1694 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001695 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001696 break;
1697 } catch (Exception e) {
1698 // ignore
1699 }
1700 checkpoint(true);
1701 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001702 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001703
1704 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001705 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001706 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001707 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001708 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001709 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001710 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001711 out.write(bytes.length >> 8);
1712 out.write(bytes.length);
1713 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001714 checkpoint(false);
1715 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001716 out.write(0xFF);
1717 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001718 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001719
1720 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001721 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001722 while (true) {
1723 try {
1724 if (in.read() == -1) {
1725 break;
1726 }
1727 } catch (Exception e) {
1728 // ignore
1729 }
1730 checkpoint(true);
1731 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001732 }
1733
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001734 // Wait for the daemons to create the new state.
1735 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001736 // Check if a running daemon is dead.
1737 for (int i = 0; i < mDaemons.length; ++i) {
1738 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001739 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001740 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001741 }
1742 }
1743 checkpoint(true);
1744 }
1745
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001746 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001747 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001748 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001749 throw new IllegalStateException("Cannot parse the state");
1750 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001751
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001752 // Set the interface and the addresses in the config.
1753 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001754
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001755 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001756 // Set the routes if they are not set in the config.
1757 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001758 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001759 }
1760
1761 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001762 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001763 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001764 if (!dnsServers.isEmpty()) {
1765 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1766 }
1767 }
1768
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001769 // Set the search domains if they are not set in the config.
1770 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1771 String searchDomains = parameters[4].trim();
1772 if (!searchDomains.isEmpty()) {
1773 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1774 }
1775 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001776
Lorenzo Colitti50262792014-09-19 01:53:35 +09001777 // Add a throw route for the VPN server endpoint, if one was specified.
1778 String endpoint = parameters[5];
1779 if (!endpoint.isEmpty()) {
1780 try {
1781 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1782 if (addr instanceof Inet4Address) {
1783 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1784 } else if (addr instanceof Inet6Address) {
1785 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1786 } else {
1787 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1788 }
1789 } catch (IllegalArgumentException e) {
1790 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1791 }
1792 }
1793
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001794 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001795 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001796 // Set the start time
1797 mConfig.startTime = SystemClock.elapsedRealtime();
1798
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001799 // Check if the thread is interrupted while we are waiting.
1800 checkpoint(false);
1801
Chia-chi Yehe9107902011-07-02 01:48:50 -07001802 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001803 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001804 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001805 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001806
1807 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001808 mInterface = mConfig.interfaze;
Robin Lee4d03abc2016-05-09 12:32:27 +01001809 prepareStatusIntent();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001810
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001811 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001812
1813 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001814 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001815 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001816 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001817 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001818 exit();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001819 }
1820 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001821
1822 /**
1823 * Monitor the daemons we started, moving to disconnected state if the
1824 * underlying services fail.
1825 */
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001826 private void monitorDaemons() throws InterruptedException{
Jeff Sharkey899223b2012-08-04 15:24:58 -07001827 if (!mNetworkInfo.isConnected()) {
1828 return;
1829 }
Hisanobu Watanabe047454c2016-06-07 19:55:41 +09001830 while (true) {
1831 Thread.sleep(2000);
1832 for (int i = 0; i < mDaemons.length; i++) {
1833 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1834 return;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001835 }
1836 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001837 }
1838 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001839 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001840}