blob: e87a2b5df2a3db544c562f5dd269c490aaf86d6e [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;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070025import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070026import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070027import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070028import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070029import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070030import android.content.Context;
31import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070032import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070033import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070034import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040035import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070037import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070038import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070039import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090040import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070041import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070042import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070043import android.net.LocalSocket;
44import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080045import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040046import android.net.NetworkAgent;
47import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070048import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040049import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070050import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070051import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040052import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070053import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080054import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070055import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070056import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040057import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070058import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070060import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070061import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070062import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070063import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070064import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070065import android.os.UserManager;
Robin Lee244ce8e2016-01-05 18:03:46 +000066import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070067import android.security.Credentials;
68import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040069import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070070import android.util.Log;
71
Chad Brubakerc2865192013-07-10 14:46:23 -070072import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070073import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070074import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080075import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070076import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070077import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078
Jeff Davidson05542602014-08-11 14:07:27 -070079import libcore.io.IoUtils;
80
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070082import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070083import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070084import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070085import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070086import java.net.Inet6Address;
87import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070088import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040089import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070090import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040092import java.util.SortedSet;
93import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070094import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070095
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096/**
97 * @hide
98 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040099public class Vpn {
100 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 private static final String TAG = "Vpn";
102 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103
Jeff Sharkey899223b2012-08-04 15:24:58 -0700104 // TODO: create separate trackers for each unique VPN to support
105 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700106
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107 private Context mContext;
108 private NetworkInfo mNetworkInfo;
109 private String mPackage;
110 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700111 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700112 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700113 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700114 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700115 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400116 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700117 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400118 private NetworkAgent mNetworkAgent;
119 private final Looper mLooper;
120 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121
122 /* list of users using this VPN. */
123 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400124 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700125
Paul Jensen0784eea2014-08-19 16:00:24 -0400126 // Handle of user initiating VPN.
127 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700128
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400130 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400133 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mLooper = looper;
135
136 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400137 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700138
139 try {
140 netService.registerObserver(mObserver);
141 } catch (RemoteException e) {
142 Log.wtf(TAG, "Problem registering observer", e);
143 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400144
145 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
146 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
147 mNetworkCapabilities = new NetworkCapabilities();
148 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
149 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700150 }
151
Jeff Sharkey57666932013-04-30 17:01:57 -0700152 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700153 * Set if this object is responsible for watching for {@link NetworkInfo}
154 * teardown. When {@code false}, teardown is handled externally by someone
155 * else.
156 */
157 public void setEnableTeardown(boolean enableTeardown) {
158 mEnableTeardown = enableTeardown;
159 }
160
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 /**
162 * Update current state, dispaching event to listeners.
163 */
164 private void updateState(DetailedState detailedState, String reason) {
165 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
166 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400167 if (mNetworkAgent != null) {
168 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
169 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700170 }
171
172 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000173 * Configures an always-on VPN connection through a specific application.
174 * This connection is automatically granted and persisted after a reboot.
175 *
176 * <p>The designated package should exist and declare a {@link VpnService} in its
177 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
178 * otherwise the call will fail.
179 *
180 * @param newPackage the package to designate as always-on VPN supplier.
181 */
182 public synchronized boolean setAlwaysOnPackage(String packageName) {
183 enforceControlPermissionOrInternalCaller();
184
185 // Disconnect current VPN.
186 prepareInternal(VpnConfig.LEGACY_VPN);
187
188 // Pre-authorize new always-on VPN package.
189 if (packageName != null) {
190 if (!setPackageAuthorization(packageName, true)) {
191 return false;
192 }
Robin Lee78378842016-02-12 11:51:33 +0000193 prepareInternal(packageName);
Robin Lee244ce8e2016-01-05 18:03:46 +0000194 }
195
196 // Save the new package name in Settings.Secure.
197 final long token = Binder.clearCallingIdentity();
198 try {
199 Settings.Secure.putStringForUser(mContext.getContentResolver(),
200 Settings.Secure.ALWAYS_ON_VPN_APP, packageName, mUserHandle);
201 } finally {
202 Binder.restoreCallingIdentity(token);
203 }
204 return true;
205 }
206
207 /**
208 * @return the package name of the VPN controller responsible for always-on VPN,
209 * or {@code null} if none is set or always-on VPN is controlled through
210 * lockdown instead.
211 * @hide
212 */
213 public synchronized String getAlwaysOnPackage() {
214 enforceControlPermissionOrInternalCaller();
215
216 final long token = Binder.clearCallingIdentity();
217 try {
218 return Settings.Secure.getStringForUser(mContext.getContentResolver(),
219 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
220 } finally {
221 Binder.restoreCallingIdentity(token);
222 }
223 }
224
225 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700226 * Prepare for a VPN application. This method is designed to solve
227 * race conditions. It first compares the current prepared package
228 * with {@code oldPackage}. If they are the same, the prepared
229 * package is revoked and replaced with {@code newPackage}. If
230 * {@code oldPackage} is {@code null}, the comparison is omitted.
231 * If {@code newPackage} is the same package or {@code null}, the
232 * revocation is omitted. This method returns {@code true} if the
233 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700234 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700235 * Legacy VPN is handled specially since it is not a real package.
236 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
237 * it can be revoked by itself.
238 *
239 * @param oldPackage The package name of the old VPN application.
240 * @param newPackage The package name of the new VPN application.
241 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700242 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700243 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700244 if (oldPackage != null) {
245 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
246 // The package doesn't match. We return false (to obtain user consent) unless the
247 // user has already consented to that VPN package.
248 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
249 prepareInternal(oldPackage);
250 return true;
251 }
252 return false;
253 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
254 && !isVpnUserPreConsented(oldPackage)) {
255 // Currently prepared VPN is revoked, so unprepare it and return false.
256 prepareInternal(VpnConfig.LEGACY_VPN);
257 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700258 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700259 }
260
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700261 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700262 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
263 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700264 return true;
265 }
266
Robin Lee1b1bcd72016-02-12 18:11:30 +0000267 // Stop an existing always-on VPN from being dethroned by other apps.
268 if (getAlwaysOnPackage() != null) {
269 return false;
270 }
271
272 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700273 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700274
Jeff Davidson11008a72014-11-20 13:12:46 -0800275 prepareInternal(newPackage);
276 return true;
277 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700278
Jeff Davidson11008a72014-11-20 13:12:46 -0800279 /** Prepare the VPN for the given package. Does not perform permission checks. */
280 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400281 long token = Binder.clearCallingIdentity();
282 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800283 // Reset the interface.
284 if (mInterface != null) {
285 mStatusIntent = null;
286 agentDisconnect();
287 jniReset(mInterface);
288 mInterface = null;
289 mVpnUsers = null;
290 }
291
292 // Revoke the connection or stop LegacyVpnRunner.
293 if (mConnection != null) {
294 try {
295 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
296 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
297 } catch (Exception e) {
298 // ignore
299 }
300 mContext.unbindService(mConnection);
301 mConnection = null;
302 } else if (mLegacyVpnRunner != null) {
303 mLegacyVpnRunner.exit();
304 mLegacyVpnRunner = null;
305 }
306
307 try {
308 mNetd.denyProtect(mOwnerUID);
309 } catch (Exception e) {
310 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
311 }
312
313 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
314 mPackage = newPackage;
315 mOwnerUID = getAppUid(newPackage, mUserHandle);
316 try {
317 mNetd.allowProtect(mOwnerUID);
318 } catch (Exception e) {
319 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
320 }
321 mConfig = null;
322
323 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400324 } finally {
325 Binder.restoreCallingIdentity(token);
326 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700327 }
328
Jeff Davidson05542602014-08-11 14:07:27 -0700329 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100330 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700331 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000332 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700333 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000334 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700335
Robin Lee3b3dd942015-05-12 18:14:58 +0100336 int uid = getAppUid(packageName, mUserHandle);
337 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
338 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000339 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700340 }
341
342 long token = Binder.clearCallingIdentity();
343 try {
344 AppOpsManager appOps =
345 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100346 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700347 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000348 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700349 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100350 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700351 } finally {
352 Binder.restoreCallingIdentity(token);
353 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000354 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700355 }
356
357 private boolean isVpnUserPreConsented(String packageName) {
358 AppOpsManager appOps =
359 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
360
361 // Verify that the caller matches the given package and has permission to activate VPNs.
362 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
363 packageName) == AppOpsManager.MODE_ALLOWED;
364 }
365
Paul Jensen0784eea2014-08-19 16:00:24 -0400366 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700367 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700369 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400370 PackageManager pm = mContext.getPackageManager();
371 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700372 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700373 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400374 } catch (NameNotFoundException e) {
375 result = -1;
376 }
377 return result;
378 }
379
380 public NetworkInfo getNetworkInfo() {
381 return mNetworkInfo;
382 }
383
Paul Jensen31a94f42015-02-13 14:18:39 -0500384 public int getNetId() {
385 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
386 }
387
Lorenzo Colitti60446162014-09-20 00:14:31 +0900388 private LinkProperties makeLinkProperties() {
389 boolean allowIPv4 = mConfig.allowIPv4;
390 boolean allowIPv6 = mConfig.allowIPv6;
391
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400392 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900393
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400394 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700395
Lorenzo Colitti60446162014-09-20 00:14:31 +0900396 if (mConfig.addresses != null) {
397 for (LinkAddress address : mConfig.addresses) {
398 lp.addLinkAddress(address);
399 allowIPv4 |= address.getAddress() instanceof Inet4Address;
400 allowIPv6 |= address.getAddress() instanceof Inet6Address;
401 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400402 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900403
404 if (mConfig.routes != null) {
405 for (RouteInfo route : mConfig.routes) {
406 lp.addRoute(route);
407 InetAddress address = route.getDestination().getAddress();
408 allowIPv4 |= address instanceof Inet4Address;
409 allowIPv6 |= address instanceof Inet6Address;
410 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400411 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700412
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400413 if (mConfig.dnsServers != null) {
414 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700415 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
416 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900417 allowIPv4 |= address instanceof Inet4Address;
418 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400419 }
420 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700421
Lorenzo Colitti60446162014-09-20 00:14:31 +0900422 if (!allowIPv4) {
423 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
424 }
425 if (!allowIPv6) {
426 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
427 }
428
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400429 // Concatenate search domains into a string.
430 StringBuilder buffer = new StringBuilder();
431 if (mConfig.searchDomains != null) {
432 for (String domain : mConfig.searchDomains) {
433 buffer.append(domain).append(' ');
434 }
435 }
436 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700437
Lorenzo Colitti60446162014-09-20 00:14:31 +0900438 // TODO: Stop setting the MTU in jniCreate and set it here.
439
440 return lp;
441 }
442
443 private void agentConnect() {
444 LinkProperties lp = makeLinkProperties();
445
446 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
447 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
448 } else {
449 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
450 }
451
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400452 mNetworkInfo.setIsAvailable(true);
453 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700454
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700455 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700456 networkMisc.allowBypass = mConfig.allowBypass;
457
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400458 long token = Binder.clearCallingIdentity();
459 try {
460 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700461 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700462 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400463 public void unwanted() {
464 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700465 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400466 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700467 } finally {
468 Binder.restoreCallingIdentity(token);
469 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700470
Paul Jensen0784eea2014-08-19 16:00:24 -0400471 addVpnUserLocked(mUserHandle);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700472 // If the user can have restricted profiles, assign all its restricted profiles to this VPN
473 if (canHaveRestrictedProfile(mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400474 token = Binder.clearCallingIdentity();
475 List<UserInfo> users;
476 try {
477 users = UserManager.get(mContext).getUsers();
478 } finally {
479 Binder.restoreCallingIdentity(token);
480 }
481 for (UserInfo user : users) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700482 if (user.isRestricted() && (user.restrictedProfileParentId == mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400483 addVpnUserLocked(user.id);
484 }
485 }
486 }
487 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
488 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700489
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700490 private boolean canHaveRestrictedProfile(int userId) {
491 long token = Binder.clearCallingIdentity();
492 try {
493 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
494 } finally {
495 Binder.restoreCallingIdentity(token);
496 }
497 }
498
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400499 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
500 networkInfo.setIsAvailable(false);
501 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
502 if (networkAgent != null) {
503 networkAgent.sendNetworkInfo(networkInfo);
504 }
505 }
506
507 private void agentDisconnect(NetworkAgent networkAgent) {
508 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
509 agentDisconnect(networkInfo, networkAgent);
510 }
511
512 private void agentDisconnect() {
513 if (mNetworkInfo.isConnected()) {
514 agentDisconnect(mNetworkInfo, mNetworkAgent);
515 mNetworkAgent = null;
516 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700517 }
518
519 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700520 * Establish a VPN network and return the file descriptor of the VPN
521 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700522 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700523 *
524 * @param config The parameters to configure the network.
525 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700526 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700527 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700528 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700529 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400530 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700531 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700532 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700533 // Check to ensure consent hasn't been revoked since we were prepared.
534 if (!isVpnUserPreConsented(mPackage)) {
535 return null;
536 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700537 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700538 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
539 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700540 long token = Binder.clearCallingIdentity();
541 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700542 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400543 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000544 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
545 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700546 throw new SecurityException("Restricted users cannot establish VPNs");
547 }
548
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700549 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400550 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700551 if (info == null) {
552 throw new SecurityException("Cannot find " + config.user);
553 }
554 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
555 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
556 }
557 } catch (RemoteException e) {
558 throw new SecurityException("Cannot find " + config.user);
559 } finally {
560 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700561 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700562
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 // Save the old config in case we need to go back.
564 VpnConfig oldConfig = mConfig;
565 String oldInterface = mInterface;
566 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400567 NetworkAgent oldNetworkAgent = mNetworkAgent;
568 mNetworkAgent = null;
569 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000570
Chia-chi Yehe9107902011-07-02 01:48:50 -0700571 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700572 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700573 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700574 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700575 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700576
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700578 StringBuilder builder = new StringBuilder();
579 for (LinkAddress address : config.addresses) {
580 builder.append(" " + address);
581 }
582 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700583 throw new IllegalArgumentException("At least one address must be specified");
584 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700585 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700586 if (!mContext.bindServiceAsUser(intent, connection,
587 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
588 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700589 throw new IllegalStateException("Cannot bind " + config.user);
590 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000591
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700592 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700593 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700594
595 // Fill more values.
596 config.user = mPackage;
597 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700598 config.startTime = SystemClock.elapsedRealtime();
599 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000600
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700601 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400602 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700603
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400604 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000605
606 if (oldConnection != null) {
607 mContext.unbindService(oldConnection);
608 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400609 // Remove the old tun's user forwarding rules
610 // The new tun's user rules have already been added so they will take over
611 // as rules are deleted. This prevents data leakage as the rules are moved over.
612 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000613 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000614 jniReset(oldInterface);
615 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700616
617 try {
618 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
619 } catch (IOException e) {
620 throw new IllegalStateException(
621 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
622 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000623 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000624 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400625 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000626 // restore old state
627 mConfig = oldConfig;
628 mConnection = oldConnection;
629 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400630 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000631 mInterface = oldInterface;
632 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700633 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000634 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700635 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700636 }
637
Chad Brubakerc2865192013-07-10 14:46:23 -0700638 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800639 return mNetworkAgent != null && mInterface != null;
640 }
641
642 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
643 // that a call to mutate VPN state is admissible.
644 private boolean isCallerEstablishedOwnerLocked() {
645 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700646 }
647
Paul Jensen0784eea2014-08-19 16:00:24 -0400648 // Note: Return type guarantees results are deduped and sorted, which callers require.
649 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
650 SortedSet<Integer> uids = new TreeSet<Integer>();
651 for (String app : packageNames) {
652 int uid = getAppUid(app, userHandle);
653 if (uid != -1) uids.add(uid);
654 }
655 return uids;
656 }
657
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400658 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400659 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800660 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700661 throw new IllegalStateException("VPN is not active");
662 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700663
Paul Jensen0784eea2014-08-19 16:00:24 -0400664 if (mConfig.allowedApplications != null) {
665 // Add ranges covering all UIDs for allowedApplications.
666 int start = -1, stop = -1;
667 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
668 if (start == -1) {
669 start = uid;
670 } else if (uid != stop + 1) {
671 mVpnUsers.add(new UidRange(start, stop));
672 start = uid;
673 }
674 stop = uid;
675 }
676 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
677 } else if (mConfig.disallowedApplications != null) {
678 // Add all ranges for user skipping UIDs for disallowedApplications.
679 final UidRange userRange = UidRange.createForUser(userHandle);
680 int start = userRange.start;
681 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
682 if (uid == start) {
683 start++;
684 } else {
685 mVpnUsers.add(new UidRange(start, uid - 1));
686 start = uid + 1;
687 }
688 }
689 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
690 } else {
691 // Add all UIDs for the user.
692 mVpnUsers.add(UidRange.createForUser(userHandle));
693 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700694
695 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700696 }
697
Paul Jensen0784eea2014-08-19 16:00:24 -0400698 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
699 // apply to userHandle.
700 private List<UidRange> uidRangesForUser(int userHandle) {
701 final UidRange userRange = UidRange.createForUser(userHandle);
702 final List<UidRange> ranges = new ArrayList<UidRange>();
703 for (UidRange range : mVpnUsers) {
704 if (range.start >= userRange.start && range.stop <= userRange.stop) {
705 ranges.add(range);
706 }
707 }
708 return ranges;
709 }
710
711 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800712 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700713 throw new IllegalStateException("VPN is not active");
714 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400715 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700716 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400717 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700718 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400719 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700720 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700721 }
722
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700723 public void onUserAdded(int userHandle) {
724 // If the user is restricted tie them to the parent user's VPN
725 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
726 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
727 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700728 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400729 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400730 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400731 final List<UidRange> ranges = uidRangesForUser(userHandle);
732 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400733 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700734 } catch (Exception e) {
735 Log.wtf(TAG, "Failed to add restricted user to owner", e);
736 }
737 }
738 }
739 }
740
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700741 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700742 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700743 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
744 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
745 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700746 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400747 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700748 } catch (Exception e) {
749 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
750 }
751 }
752 }
753 }
754
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700755 /**
756 * Return the configuration of the currently running VPN.
757 */
758 public VpnConfig getVpnConfig() {
759 enforceControlPermission();
760 return mConfig;
761 }
762
Jeff Sharkey899223b2012-08-04 15:24:58 -0700763 @Deprecated
764 public synchronized void interfaceStatusChanged(String iface, boolean up) {
765 try {
766 mObserver.interfaceStatusChanged(iface, up);
767 } catch (RemoteException e) {
768 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700769 }
770 }
771
Jeff Sharkey899223b2012-08-04 15:24:58 -0700772 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
773 @Override
774 public void interfaceStatusChanged(String interfaze, boolean up) {
775 synchronized (Vpn.this) {
776 if (!up && mLegacyVpnRunner != null) {
777 mLegacyVpnRunner.check(interfaze);
778 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700779 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700780 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700781
Jeff Sharkey899223b2012-08-04 15:24:58 -0700782 @Override
783 public void interfaceRemoved(String interfaze) {
784 synchronized (Vpn.this) {
785 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700786 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400787 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500788 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700789 mInterface = null;
790 if (mConnection != null) {
791 mContext.unbindService(mConnection);
792 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400793 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700794 } else if (mLegacyVpnRunner != null) {
795 mLegacyVpnRunner.exit();
796 mLegacyVpnRunner = null;
797 }
798 }
799 }
800 }
801 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700802
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700803 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800804 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700805 }
806
Robin Lee244ce8e2016-01-05 18:03:46 +0000807 private void enforceControlPermissionOrInternalCaller() {
808 // Require caller to be either an application with CONTROL_VPN permission or a process
809 // in the system server.
810 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
811 "Unauthorized Caller");
812 }
813
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700814 private class Connection implements ServiceConnection {
815 private IBinder mService;
816
817 @Override
818 public void onServiceConnected(ComponentName name, IBinder service) {
819 mService = service;
820 }
821
822 @Override
823 public void onServiceDisconnected(ComponentName name) {
824 mService = null;
825 }
826 }
827
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700828 private void prepareStatusIntent() {
829 final long token = Binder.clearCallingIdentity();
830 try {
831 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
832 } finally {
833 Binder.restoreCallingIdentity(token);
834 }
835 }
836
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700837 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800838 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700839 return false;
840 }
841 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800842 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700843 return success;
844 }
845
846 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800847 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700848 return false;
849 }
850 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800851 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700852 return success;
853 }
854
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800855 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
856 if (!isCallerEstablishedOwnerLocked()) {
857 return false;
858 }
859 if (networks == null) {
860 mConfig.underlyingNetworks = null;
861 } else {
862 mConfig.underlyingNetworks = new Network[networks.length];
863 for (int i = 0; i < networks.length; ++i) {
864 if (networks[i] == null) {
865 mConfig.underlyingNetworks[i] = null;
866 } else {
867 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
868 }
869 }
870 }
871 return true;
872 }
873
874 public synchronized Network[] getUnderlyingNetworks() {
875 if (!isRunningLocked()) {
876 return null;
877 }
878 return mConfig.underlyingNetworks;
879 }
880
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800881 /**
882 * This method should only be called by ConnectivityService. Because it doesn't
883 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
884 */
885 public synchronized VpnInfo getVpnInfo() {
886 if (!isRunningLocked()) {
887 return null;
888 }
889
890 VpnInfo info = new VpnInfo();
891 info.ownerUid = mOwnerUID;
892 info.vpnIface = mInterface;
893 return info;
894 }
895
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800896 public synchronized boolean appliesToUid(int uid) {
897 if (!isRunningLocked()) {
898 return false;
899 }
900 for (UidRange uidRange : mVpnUsers) {
901 if (uidRange.start <= uid && uid <= uidRange.stop) {
902 return true;
903 }
904 }
905 return false;
906 }
907
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700908 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700909 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700910 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700911 private native void jniReset(String interfaze);
912 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700913 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
914 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700915
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900916 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
917 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700918 // Currently legacy VPN only works on IPv4.
919 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900920 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700921 }
922 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700923
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900924 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700925 }
926
927 /**
928 * Start legacy VPN, controlling native daemons as needed. Creates a
929 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800930 *
931 * Should only be called to respond to Binder requests as this enforces caller permission. Use
932 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
933 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700934 */
935 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800936 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800937 long token = Binder.clearCallingIdentity();
938 try {
939 startLegacyVpnPrivileged(profile, keyStore, egress);
940 } finally {
941 Binder.restoreCallingIdentity(token);
942 }
943 }
944
945 /**
946 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
947 * permissions under the assumption that the caller is the system.
948 *
949 * Callers are responsible for checking permissions if needed.
950 */
951 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
952 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400953 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400954 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000955 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
956 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400957 throw new SecurityException("Restricted users cannot establish VPNs");
958 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700959
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900960 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
961 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
962 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700963
964 // Load certificates.
965 String privateKey = "";
966 String userCert = "";
967 String caCert = "";
968 String serverCert = "";
969 if (!profile.ipsecUserCert.isEmpty()) {
970 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
971 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700972 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700973 }
974 if (!profile.ipsecCaCert.isEmpty()) {
975 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700976 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700977 }
978 if (!profile.ipsecServerCert.isEmpty()) {
979 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700980 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700981 }
982 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
983 throw new IllegalStateException("Cannot load credentials");
984 }
985
986 // Prepare arguments for racoon.
987 String[] racoon = null;
988 switch (profile.type) {
989 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
990 racoon = new String[] {
991 iface, profile.server, "udppsk", profile.ipsecIdentifier,
992 profile.ipsecSecret, "1701",
993 };
994 break;
995 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
996 racoon = new String[] {
997 iface, profile.server, "udprsa", privateKey, userCert,
998 caCert, serverCert, "1701",
999 };
1000 break;
1001 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1002 racoon = new String[] {
1003 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1004 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1005 };
1006 break;
1007 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1008 racoon = new String[] {
1009 iface, profile.server, "xauthrsa", privateKey, userCert,
1010 caCert, serverCert, profile.username, profile.password, "", gateway,
1011 };
1012 break;
1013 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1014 racoon = new String[] {
1015 iface, profile.server, "hybridrsa",
1016 caCert, serverCert, profile.username, profile.password, "", gateway,
1017 };
1018 break;
1019 }
1020
1021 // Prepare arguments for mtpd.
1022 String[] mtpd = null;
1023 switch (profile.type) {
1024 case VpnProfile.TYPE_PPTP:
1025 mtpd = new String[] {
1026 iface, "pptp", profile.server, "1723",
1027 "name", profile.username, "password", profile.password,
1028 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1029 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1030 (profile.mppe ? "+mppe" : "nomppe"),
1031 };
1032 break;
1033 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1034 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1035 mtpd = new String[] {
1036 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1037 "name", profile.username, "password", profile.password,
1038 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1039 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1040 };
1041 break;
1042 }
1043
1044 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001045 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001046 config.user = profile.key;
1047 config.interfaze = iface;
1048 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001049
1050 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001051 if (!profile.dnsServers.isEmpty()) {
1052 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1053 }
1054 if (!profile.searchDomains.isEmpty()) {
1055 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1056 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001057 startLegacyVpn(config, racoon, mtpd);
1058 }
1059
1060 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001061 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001062
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001063 // Prepare for the new request.
1064 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001065 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001066
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001067 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001068 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1069 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070 }
1071
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001072 /** Stop legacy VPN. Permissions must be checked by callers. */
1073 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001074 if (mLegacyVpnRunner != null) {
1075 mLegacyVpnRunner.exit();
1076 mLegacyVpnRunner = null;
1077
1078 synchronized (LegacyVpnRunner.TAG) {
1079 // wait for old thread to completely finish before spinning up
1080 // new instance, otherwise state updates can be out of order.
1081 }
1082 }
1083 }
1084
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001085 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001086 * Return the information of the current ongoing legacy VPN.
1087 */
1088 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001089 // Check if the caller is authorized.
1090 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001091 return getLegacyVpnInfoPrivileged();
1092 }
1093
1094 /**
1095 * Return the information of the current ongoing legacy VPN.
1096 * Callers are responsible for checking permissions if needed.
1097 */
1098 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001099 if (mLegacyVpnRunner == null) return null;
1100
1101 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001102 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001103 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001104 if (mNetworkInfo.isConnected()) {
1105 info.intent = mStatusIntent;
1106 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001107 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001108 }
1109
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001110 public VpnConfig getLegacyVpnConfig() {
1111 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001112 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001113 } else {
1114 return null;
1115 }
1116 }
1117
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001118 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001119 * Bringing up a VPN connection takes time, and that is all this thread
1120 * does. Here we have plenty of time. The only thing we need to take
1121 * care of is responding to interruptions as soon as possible. Otherwise
1122 * requests will be piled up. This can be done in a Handler as a state
1123 * machine, but it is much easier to read in the current form.
1124 */
1125 private class LegacyVpnRunner extends Thread {
1126 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001127
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001128 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001129 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001130 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001131 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001132 private final AtomicInteger mOuterConnection =
1133 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001134
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001135 private long mTimer = -1;
1136
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001137 /**
1138 * Watch for the outer connection (passing in the constructor) going away.
1139 */
1140 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1141 @Override
1142 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001143 if (!mEnableTeardown) return;
1144
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001145 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1146 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1147 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1148 NetworkInfo info = (NetworkInfo)intent.getExtra(
1149 ConnectivityManager.EXTRA_NETWORK_INFO);
1150 if (info != null && !info.isConnectedOrConnecting()) {
1151 try {
1152 mObserver.interfaceStatusChanged(mOuterInterface, false);
1153 } catch (RemoteException e) {}
1154 }
1155 }
1156 }
1157 }
1158 };
1159
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001160 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001161 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001162 mConfig = config;
1163 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001164 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001165 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001166 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001167
1168 // This is the interface which VPN is running on,
1169 // mConfig.interfaze will change to point to OUR
1170 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001171 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001172 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001173 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001174 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001175
Paul Jensene75b9e32015-04-06 11:54:53 -04001176 if (!TextUtils.isEmpty(mOuterInterface)) {
1177 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1178 for (Network network : cm.getAllNetworks()) {
1179 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001180 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001181 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1182 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1183 }
1184 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001185 }
1186
1187 IntentFilter filter = new IntentFilter();
1188 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1189 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001190 }
1191
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001192 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001193 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001194 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1195 exit();
1196 }
1197 }
1198
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001199 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001200 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001201 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001202 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001203 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001204 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001205 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001206 try {
1207 mContext.unregisterReceiver(mBroadcastReceiver);
1208 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001209 }
1210
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001211 @Override
1212 public void run() {
1213 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001214 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001215 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001216 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001217 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001218 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001219 }
1220 }
1221
1222 private void checkpoint(boolean yield) throws InterruptedException {
1223 long now = SystemClock.elapsedRealtime();
1224 if (mTimer == -1) {
1225 mTimer = now;
1226 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001227 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001228 Thread.sleep(yield ? 200 : 1);
1229 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001230 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001231 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001232 }
1233 }
1234
1235 private void execute() {
1236 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001237 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001238 try {
1239 // Initialize the timer.
1240 checkpoint(false);
1241
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001242 // Wait for the daemons to stop.
1243 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001244 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001245 checkpoint(true);
1246 }
1247 }
1248
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001249 // Clear the previous state.
1250 File state = new File("/data/misc/vpn/state");
1251 state.delete();
1252 if (state.exists()) {
1253 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001254 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001255 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001256 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001257
Chia-chi Yehe9107902011-07-02 01:48:50 -07001258 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001259 boolean restart = false;
1260 for (String[] arguments : mArguments) {
1261 restart = restart || (arguments != null);
1262 }
1263 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001264 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001265 return;
1266 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001267 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001268
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001269 // Start the daemon with arguments.
1270 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001271 String[] arguments = mArguments[i];
1272 if (arguments == null) {
1273 continue;
1274 }
1275
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001276 // Start the daemon.
1277 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001278 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001279
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001280 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001281 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001282 checkpoint(true);
1283 }
1284
1285 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001286 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001287 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001288 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001289
1290 // Wait for the socket to connect.
1291 while (true) {
1292 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001293 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001294 break;
1295 } catch (Exception e) {
1296 // ignore
1297 }
1298 checkpoint(true);
1299 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001300 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001301
1302 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001303 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001304 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001305 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001306 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001307 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001308 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001309 out.write(bytes.length >> 8);
1310 out.write(bytes.length);
1311 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001312 checkpoint(false);
1313 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001314 out.write(0xFF);
1315 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001316 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001317
1318 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001319 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001320 while (true) {
1321 try {
1322 if (in.read() == -1) {
1323 break;
1324 }
1325 } catch (Exception e) {
1326 // ignore
1327 }
1328 checkpoint(true);
1329 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001330 }
1331
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001332 // Wait for the daemons to create the new state.
1333 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001334 // Check if a running daemon is dead.
1335 for (int i = 0; i < mDaemons.length; ++i) {
1336 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001337 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001338 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001339 }
1340 }
1341 checkpoint(true);
1342 }
1343
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001344 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001345 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001346 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001347 throw new IllegalStateException("Cannot parse the state");
1348 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001349
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001350 // Set the interface and the addresses in the config.
1351 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001352
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001353 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001354 // Set the routes if they are not set in the config.
1355 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001356 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001357 }
1358
1359 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001360 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001361 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001362 if (!dnsServers.isEmpty()) {
1363 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1364 }
1365 }
1366
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001367 // Set the search domains if they are not set in the config.
1368 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1369 String searchDomains = parameters[4].trim();
1370 if (!searchDomains.isEmpty()) {
1371 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1372 }
1373 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001374
Lorenzo Colitti50262792014-09-19 01:53:35 +09001375 // Add a throw route for the VPN server endpoint, if one was specified.
1376 String endpoint = parameters[5];
1377 if (!endpoint.isEmpty()) {
1378 try {
1379 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1380 if (addr instanceof Inet4Address) {
1381 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1382 } else if (addr instanceof Inet6Address) {
1383 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1384 } else {
1385 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1386 }
1387 } catch (IllegalArgumentException e) {
1388 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1389 }
1390 }
1391
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001392 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001393 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001394 // Set the start time
1395 mConfig.startTime = SystemClock.elapsedRealtime();
1396
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001397 // Check if the thread is interrupted while we are waiting.
1398 checkpoint(false);
1399
Chia-chi Yehe9107902011-07-02 01:48:50 -07001400 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001401 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001402 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001403 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001404
1405 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001406 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001407 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001408
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001409 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001410
1411 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001412 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001413 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001414 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001415 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001416 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001417 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001418 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001419 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001420 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001421 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001422 }
1423 }
1424
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001425 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001426 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001427 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001428 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001429 }
1430 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001431
1432 /**
1433 * Monitor the daemons we started, moving to disconnected state if the
1434 * underlying services fail.
1435 */
1436 private void monitorDaemons() {
1437 if (!mNetworkInfo.isConnected()) {
1438 return;
1439 }
1440
1441 try {
1442 while (true) {
1443 Thread.sleep(2000);
1444 for (int i = 0; i < mDaemons.length; i++) {
1445 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1446 return;
1447 }
1448 }
1449 }
1450 } catch (InterruptedException e) {
1451 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1452 } finally {
1453 for (String daemon : mDaemons) {
1454 SystemService.stop(daemon);
1455 }
1456
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001457 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001458 }
1459 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001460 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001461}