blob: 2600d702eca1251a883d0b664e76ed4ff1d92bc8 [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 }
193 }
194
195 // Save the new package name in Settings.Secure.
196 final long token = Binder.clearCallingIdentity();
197 try {
198 Settings.Secure.putStringForUser(mContext.getContentResolver(),
199 Settings.Secure.ALWAYS_ON_VPN_APP, packageName, mUserHandle);
200 } finally {
201 Binder.restoreCallingIdentity(token);
202 }
203 return true;
204 }
205
206 /**
207 * @return the package name of the VPN controller responsible for always-on VPN,
208 * or {@code null} if none is set or always-on VPN is controlled through
209 * lockdown instead.
210 * @hide
211 */
212 public synchronized String getAlwaysOnPackage() {
213 enforceControlPermissionOrInternalCaller();
214
215 final long token = Binder.clearCallingIdentity();
216 try {
217 return Settings.Secure.getStringForUser(mContext.getContentResolver(),
218 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
219 } finally {
220 Binder.restoreCallingIdentity(token);
221 }
222 }
223
224 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700225 * Prepare for a VPN application. This method is designed to solve
226 * race conditions. It first compares the current prepared package
227 * with {@code oldPackage}. If they are the same, the prepared
228 * package is revoked and replaced with {@code newPackage}. If
229 * {@code oldPackage} is {@code null}, the comparison is omitted.
230 * If {@code newPackage} is the same package or {@code null}, the
231 * revocation is omitted. This method returns {@code true} if the
232 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700233 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700234 * Legacy VPN is handled specially since it is not a real package.
235 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
236 * it can be revoked by itself.
237 *
238 * @param oldPackage The package name of the old VPN application.
239 * @param newPackage The package name of the new VPN application.
240 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700241 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700242 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700243 if (oldPackage != null) {
244 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
245 // The package doesn't match. We return false (to obtain user consent) unless the
246 // user has already consented to that VPN package.
247 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
248 prepareInternal(oldPackage);
249 return true;
250 }
251 return false;
252 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
253 && !isVpnUserPreConsented(oldPackage)) {
254 // Currently prepared VPN is revoked, so unprepare it and return false.
255 prepareInternal(VpnConfig.LEGACY_VPN);
256 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700257 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700258 }
259
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700260 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700261 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
262 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700263 return true;
264 }
265
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700266 // Check if the caller is authorized.
267 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700268
Jeff Davidson11008a72014-11-20 13:12:46 -0800269 prepareInternal(newPackage);
270 return true;
271 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700272
Jeff Davidson11008a72014-11-20 13:12:46 -0800273 /** Prepare the VPN for the given package. Does not perform permission checks. */
274 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400275 long token = Binder.clearCallingIdentity();
276 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800277 // Reset the interface.
278 if (mInterface != null) {
279 mStatusIntent = null;
280 agentDisconnect();
281 jniReset(mInterface);
282 mInterface = null;
283 mVpnUsers = null;
284 }
285
286 // Revoke the connection or stop LegacyVpnRunner.
287 if (mConnection != null) {
288 try {
289 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
290 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
291 } catch (Exception e) {
292 // ignore
293 }
294 mContext.unbindService(mConnection);
295 mConnection = null;
296 } else if (mLegacyVpnRunner != null) {
297 mLegacyVpnRunner.exit();
298 mLegacyVpnRunner = null;
299 }
300
301 try {
302 mNetd.denyProtect(mOwnerUID);
303 } catch (Exception e) {
304 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
305 }
306
307 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
308 mPackage = newPackage;
309 mOwnerUID = getAppUid(newPackage, mUserHandle);
310 try {
311 mNetd.allowProtect(mOwnerUID);
312 } catch (Exception e) {
313 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
314 }
315 mConfig = null;
316
317 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400318 } finally {
319 Binder.restoreCallingIdentity(token);
320 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700321 }
322
Jeff Davidson05542602014-08-11 14:07:27 -0700323 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100324 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700325 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000326 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700327 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000328 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700329
Robin Lee3b3dd942015-05-12 18:14:58 +0100330 int uid = getAppUid(packageName, mUserHandle);
331 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
332 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000333 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700334 }
335
336 long token = Binder.clearCallingIdentity();
337 try {
338 AppOpsManager appOps =
339 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100340 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700341 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000342 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700343 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100344 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700345 } finally {
346 Binder.restoreCallingIdentity(token);
347 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000348 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700349 }
350
351 private boolean isVpnUserPreConsented(String packageName) {
352 AppOpsManager appOps =
353 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
354
355 // Verify that the caller matches the given package and has permission to activate VPNs.
356 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
357 packageName) == AppOpsManager.MODE_ALLOWED;
358 }
359
Paul Jensen0784eea2014-08-19 16:00:24 -0400360 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700361 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400362 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700363 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400364 PackageManager pm = mContext.getPackageManager();
365 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700366 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400367 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 } catch (NameNotFoundException e) {
369 result = -1;
370 }
371 return result;
372 }
373
374 public NetworkInfo getNetworkInfo() {
375 return mNetworkInfo;
376 }
377
Paul Jensen31a94f42015-02-13 14:18:39 -0500378 public int getNetId() {
379 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
380 }
381
Lorenzo Colitti60446162014-09-20 00:14:31 +0900382 private LinkProperties makeLinkProperties() {
383 boolean allowIPv4 = mConfig.allowIPv4;
384 boolean allowIPv6 = mConfig.allowIPv6;
385
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400386 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900387
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700389
Lorenzo Colitti60446162014-09-20 00:14:31 +0900390 if (mConfig.addresses != null) {
391 for (LinkAddress address : mConfig.addresses) {
392 lp.addLinkAddress(address);
393 allowIPv4 |= address.getAddress() instanceof Inet4Address;
394 allowIPv6 |= address.getAddress() instanceof Inet6Address;
395 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400396 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900397
398 if (mConfig.routes != null) {
399 for (RouteInfo route : mConfig.routes) {
400 lp.addRoute(route);
401 InetAddress address = route.getDestination().getAddress();
402 allowIPv4 |= address instanceof Inet4Address;
403 allowIPv6 |= address instanceof Inet6Address;
404 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400405 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700406
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400407 if (mConfig.dnsServers != null) {
408 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700409 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
410 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900411 allowIPv4 |= address instanceof Inet4Address;
412 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400413 }
414 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700415
Lorenzo Colitti60446162014-09-20 00:14:31 +0900416 if (!allowIPv4) {
417 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
418 }
419 if (!allowIPv6) {
420 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
421 }
422
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400423 // Concatenate search domains into a string.
424 StringBuilder buffer = new StringBuilder();
425 if (mConfig.searchDomains != null) {
426 for (String domain : mConfig.searchDomains) {
427 buffer.append(domain).append(' ');
428 }
429 }
430 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700431
Lorenzo Colitti60446162014-09-20 00:14:31 +0900432 // TODO: Stop setting the MTU in jniCreate and set it here.
433
434 return lp;
435 }
436
437 private void agentConnect() {
438 LinkProperties lp = makeLinkProperties();
439
440 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
441 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
442 } else {
443 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
444 }
445
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400446 mNetworkInfo.setIsAvailable(true);
447 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700448
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700449 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700450 networkMisc.allowBypass = mConfig.allowBypass;
451
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400452 long token = Binder.clearCallingIdentity();
453 try {
454 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700455 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700456 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400457 public void unwanted() {
458 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700459 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400460 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700461 } finally {
462 Binder.restoreCallingIdentity(token);
463 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700464
Paul Jensen0784eea2014-08-19 16:00:24 -0400465 addVpnUserLocked(mUserHandle);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700466 // If the user can have restricted profiles, assign all its restricted profiles to this VPN
467 if (canHaveRestrictedProfile(mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400468 token = Binder.clearCallingIdentity();
469 List<UserInfo> users;
470 try {
471 users = UserManager.get(mContext).getUsers();
472 } finally {
473 Binder.restoreCallingIdentity(token);
474 }
475 for (UserInfo user : users) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700476 if (user.isRestricted() && (user.restrictedProfileParentId == mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400477 addVpnUserLocked(user.id);
478 }
479 }
480 }
481 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
482 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700483
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700484 private boolean canHaveRestrictedProfile(int userId) {
485 long token = Binder.clearCallingIdentity();
486 try {
487 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
488 } finally {
489 Binder.restoreCallingIdentity(token);
490 }
491 }
492
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400493 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
494 networkInfo.setIsAvailable(false);
495 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
496 if (networkAgent != null) {
497 networkAgent.sendNetworkInfo(networkInfo);
498 }
499 }
500
501 private void agentDisconnect(NetworkAgent networkAgent) {
502 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
503 agentDisconnect(networkInfo, networkAgent);
504 }
505
506 private void agentDisconnect() {
507 if (mNetworkInfo.isConnected()) {
508 agentDisconnect(mNetworkInfo, mNetworkAgent);
509 mNetworkAgent = null;
510 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700511 }
512
513 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700514 * Establish a VPN network and return the file descriptor of the VPN
515 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700516 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700517 *
518 * @param config The parameters to configure the network.
519 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700520 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700521 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700522 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700523 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400524 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700525 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700526 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700527 // Check to ensure consent hasn't been revoked since we were prepared.
528 if (!isVpnUserPreConsented(mPackage)) {
529 return null;
530 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700531 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700532 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
533 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700534 long token = Binder.clearCallingIdentity();
535 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700536 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400537 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000538 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
539 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700540 throw new SecurityException("Restricted users cannot establish VPNs");
541 }
542
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700543 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400544 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700545 if (info == null) {
546 throw new SecurityException("Cannot find " + config.user);
547 }
548 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
549 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
550 }
551 } catch (RemoteException e) {
552 throw new SecurityException("Cannot find " + config.user);
553 } finally {
554 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700555 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700556
Chad Brubaker850eb672014-03-21 21:02:47 +0000557 // Save the old config in case we need to go back.
558 VpnConfig oldConfig = mConfig;
559 String oldInterface = mInterface;
560 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400561 NetworkAgent oldNetworkAgent = mNetworkAgent;
562 mNetworkAgent = null;
563 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000564
Chia-chi Yehe9107902011-07-02 01:48:50 -0700565 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700566 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700567 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700568 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700569 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700570
Chad Brubakerc2865192013-07-10 14:46:23 -0700571 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700572 StringBuilder builder = new StringBuilder();
573 for (LinkAddress address : config.addresses) {
574 builder.append(" " + address);
575 }
576 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700577 throw new IllegalArgumentException("At least one address must be specified");
578 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700579 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700580 if (!mContext.bindServiceAsUser(intent, connection,
581 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
582 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700583 throw new IllegalStateException("Cannot bind " + config.user);
584 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000585
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700586 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700587 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700588
589 // Fill more values.
590 config.user = mPackage;
591 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700592 config.startTime = SystemClock.elapsedRealtime();
593 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000594
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700595 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400596 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700597
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400598 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000599
600 if (oldConnection != null) {
601 mContext.unbindService(oldConnection);
602 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400603 // Remove the old tun's user forwarding rules
604 // The new tun's user rules have already been added so they will take over
605 // as rules are deleted. This prevents data leakage as the rules are moved over.
606 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000607 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000608 jniReset(oldInterface);
609 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700610
611 try {
612 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
613 } catch (IOException e) {
614 throw new IllegalStateException(
615 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
616 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000617 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000618 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400619 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000620 // restore old state
621 mConfig = oldConfig;
622 mConnection = oldConnection;
623 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400624 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000625 mInterface = oldInterface;
626 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700627 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000628 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700629 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700630 }
631
Chad Brubakerc2865192013-07-10 14:46:23 -0700632 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800633 return mNetworkAgent != null && mInterface != null;
634 }
635
636 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
637 // that a call to mutate VPN state is admissible.
638 private boolean isCallerEstablishedOwnerLocked() {
639 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700640 }
641
Paul Jensen0784eea2014-08-19 16:00:24 -0400642 // Note: Return type guarantees results are deduped and sorted, which callers require.
643 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
644 SortedSet<Integer> uids = new TreeSet<Integer>();
645 for (String app : packageNames) {
646 int uid = getAppUid(app, userHandle);
647 if (uid != -1) uids.add(uid);
648 }
649 return uids;
650 }
651
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400652 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400653 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800654 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700655 throw new IllegalStateException("VPN is not active");
656 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700657
Paul Jensen0784eea2014-08-19 16:00:24 -0400658 if (mConfig.allowedApplications != null) {
659 // Add ranges covering all UIDs for allowedApplications.
660 int start = -1, stop = -1;
661 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
662 if (start == -1) {
663 start = uid;
664 } else if (uid != stop + 1) {
665 mVpnUsers.add(new UidRange(start, stop));
666 start = uid;
667 }
668 stop = uid;
669 }
670 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
671 } else if (mConfig.disallowedApplications != null) {
672 // Add all ranges for user skipping UIDs for disallowedApplications.
673 final UidRange userRange = UidRange.createForUser(userHandle);
674 int start = userRange.start;
675 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
676 if (uid == start) {
677 start++;
678 } else {
679 mVpnUsers.add(new UidRange(start, uid - 1));
680 start = uid + 1;
681 }
682 }
683 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
684 } else {
685 // Add all UIDs for the user.
686 mVpnUsers.add(UidRange.createForUser(userHandle));
687 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700688
689 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700690 }
691
Paul Jensen0784eea2014-08-19 16:00:24 -0400692 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
693 // apply to userHandle.
694 private List<UidRange> uidRangesForUser(int userHandle) {
695 final UidRange userRange = UidRange.createForUser(userHandle);
696 final List<UidRange> ranges = new ArrayList<UidRange>();
697 for (UidRange range : mVpnUsers) {
698 if (range.start >= userRange.start && range.stop <= userRange.stop) {
699 ranges.add(range);
700 }
701 }
702 return ranges;
703 }
704
705 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800706 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700707 throw new IllegalStateException("VPN is not active");
708 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400709 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700710 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400711 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700712 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400713 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700714 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700715 }
716
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700717 public void onUserAdded(int userHandle) {
718 // If the user is restricted tie them to the parent user's VPN
719 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
720 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
721 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700722 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400723 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400724 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400725 final List<UidRange> ranges = uidRangesForUser(userHandle);
726 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400727 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700728 } catch (Exception e) {
729 Log.wtf(TAG, "Failed to add restricted user to owner", e);
730 }
731 }
732 }
733 }
734
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700735 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700736 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700737 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
738 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
739 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700740 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400741 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700742 } catch (Exception e) {
743 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
744 }
745 }
746 }
747 }
748
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700749 /**
750 * Return the configuration of the currently running VPN.
751 */
752 public VpnConfig getVpnConfig() {
753 enforceControlPermission();
754 return mConfig;
755 }
756
Jeff Sharkey899223b2012-08-04 15:24:58 -0700757 @Deprecated
758 public synchronized void interfaceStatusChanged(String iface, boolean up) {
759 try {
760 mObserver.interfaceStatusChanged(iface, up);
761 } catch (RemoteException e) {
762 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700763 }
764 }
765
Jeff Sharkey899223b2012-08-04 15:24:58 -0700766 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
767 @Override
768 public void interfaceStatusChanged(String interfaze, boolean up) {
769 synchronized (Vpn.this) {
770 if (!up && mLegacyVpnRunner != null) {
771 mLegacyVpnRunner.check(interfaze);
772 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700773 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700774 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700775
Jeff Sharkey899223b2012-08-04 15:24:58 -0700776 @Override
777 public void interfaceRemoved(String interfaze) {
778 synchronized (Vpn.this) {
779 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700780 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400781 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500782 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700783 mInterface = null;
784 if (mConnection != null) {
785 mContext.unbindService(mConnection);
786 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400787 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700788 } else if (mLegacyVpnRunner != null) {
789 mLegacyVpnRunner.exit();
790 mLegacyVpnRunner = null;
791 }
792 }
793 }
794 }
795 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700796
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700797 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800798 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700799 }
800
Robin Lee244ce8e2016-01-05 18:03:46 +0000801 private void enforceControlPermissionOrInternalCaller() {
802 // Require caller to be either an application with CONTROL_VPN permission or a process
803 // in the system server.
804 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
805 "Unauthorized Caller");
806 }
807
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700808 private class Connection implements ServiceConnection {
809 private IBinder mService;
810
811 @Override
812 public void onServiceConnected(ComponentName name, IBinder service) {
813 mService = service;
814 }
815
816 @Override
817 public void onServiceDisconnected(ComponentName name) {
818 mService = null;
819 }
820 }
821
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700822 private void prepareStatusIntent() {
823 final long token = Binder.clearCallingIdentity();
824 try {
825 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
826 } finally {
827 Binder.restoreCallingIdentity(token);
828 }
829 }
830
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700831 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800832 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700833 return false;
834 }
835 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800836 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700837 return success;
838 }
839
840 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800841 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700842 return false;
843 }
844 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800845 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700846 return success;
847 }
848
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800849 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
850 if (!isCallerEstablishedOwnerLocked()) {
851 return false;
852 }
853 if (networks == null) {
854 mConfig.underlyingNetworks = null;
855 } else {
856 mConfig.underlyingNetworks = new Network[networks.length];
857 for (int i = 0; i < networks.length; ++i) {
858 if (networks[i] == null) {
859 mConfig.underlyingNetworks[i] = null;
860 } else {
861 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
862 }
863 }
864 }
865 return true;
866 }
867
868 public synchronized Network[] getUnderlyingNetworks() {
869 if (!isRunningLocked()) {
870 return null;
871 }
872 return mConfig.underlyingNetworks;
873 }
874
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800875 /**
876 * This method should only be called by ConnectivityService. Because it doesn't
877 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
878 */
879 public synchronized VpnInfo getVpnInfo() {
880 if (!isRunningLocked()) {
881 return null;
882 }
883
884 VpnInfo info = new VpnInfo();
885 info.ownerUid = mOwnerUID;
886 info.vpnIface = mInterface;
887 return info;
888 }
889
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800890 public synchronized boolean appliesToUid(int uid) {
891 if (!isRunningLocked()) {
892 return false;
893 }
894 for (UidRange uidRange : mVpnUsers) {
895 if (uidRange.start <= uid && uid <= uidRange.stop) {
896 return true;
897 }
898 }
899 return false;
900 }
901
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700902 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700903 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700904 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700905 private native void jniReset(String interfaze);
906 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700907 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
908 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700909
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900910 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
911 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700912 // Currently legacy VPN only works on IPv4.
913 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900914 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700915 }
916 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700917
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900918 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700919 }
920
921 /**
922 * Start legacy VPN, controlling native daemons as needed. Creates a
923 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800924 *
925 * Should only be called to respond to Binder requests as this enforces caller permission. Use
926 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
927 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700928 */
929 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800930 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800931 long token = Binder.clearCallingIdentity();
932 try {
933 startLegacyVpnPrivileged(profile, keyStore, egress);
934 } finally {
935 Binder.restoreCallingIdentity(token);
936 }
937 }
938
939 /**
940 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
941 * permissions under the assumption that the caller is the system.
942 *
943 * Callers are responsible for checking permissions if needed.
944 */
945 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
946 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800947 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700948 throw new IllegalStateException("KeyStore isn't unlocked");
949 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400950 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400951 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000952 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
953 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400954 throw new SecurityException("Restricted users cannot establish VPNs");
955 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700956
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900957 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
958 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
959 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700960
961 // Load certificates.
962 String privateKey = "";
963 String userCert = "";
964 String caCert = "";
965 String serverCert = "";
966 if (!profile.ipsecUserCert.isEmpty()) {
967 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
968 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700969 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700970 }
971 if (!profile.ipsecCaCert.isEmpty()) {
972 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700973 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700974 }
975 if (!profile.ipsecServerCert.isEmpty()) {
976 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700977 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700978 }
979 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
980 throw new IllegalStateException("Cannot load credentials");
981 }
982
983 // Prepare arguments for racoon.
984 String[] racoon = null;
985 switch (profile.type) {
986 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
987 racoon = new String[] {
988 iface, profile.server, "udppsk", profile.ipsecIdentifier,
989 profile.ipsecSecret, "1701",
990 };
991 break;
992 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
993 racoon = new String[] {
994 iface, profile.server, "udprsa", privateKey, userCert,
995 caCert, serverCert, "1701",
996 };
997 break;
998 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
999 racoon = new String[] {
1000 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1001 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1002 };
1003 break;
1004 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1005 racoon = new String[] {
1006 iface, profile.server, "xauthrsa", privateKey, userCert,
1007 caCert, serverCert, profile.username, profile.password, "", gateway,
1008 };
1009 break;
1010 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1011 racoon = new String[] {
1012 iface, profile.server, "hybridrsa",
1013 caCert, serverCert, profile.username, profile.password, "", gateway,
1014 };
1015 break;
1016 }
1017
1018 // Prepare arguments for mtpd.
1019 String[] mtpd = null;
1020 switch (profile.type) {
1021 case VpnProfile.TYPE_PPTP:
1022 mtpd = new String[] {
1023 iface, "pptp", profile.server, "1723",
1024 "name", profile.username, "password", profile.password,
1025 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1026 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1027 (profile.mppe ? "+mppe" : "nomppe"),
1028 };
1029 break;
1030 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1031 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1032 mtpd = new String[] {
1033 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1034 "name", profile.username, "password", profile.password,
1035 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1036 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1037 };
1038 break;
1039 }
1040
1041 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001042 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001043 config.user = profile.key;
1044 config.interfaze = iface;
1045 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001046
1047 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001048 if (!profile.dnsServers.isEmpty()) {
1049 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1050 }
1051 if (!profile.searchDomains.isEmpty()) {
1052 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1053 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001054 startLegacyVpn(config, racoon, mtpd);
1055 }
1056
1057 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001058 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001059
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001060 // Prepare for the new request.
1061 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001062 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001063
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001064 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001065 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1066 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001067 }
1068
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001069 /** Stop legacy VPN. Permissions must be checked by callers. */
1070 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001071 if (mLegacyVpnRunner != null) {
1072 mLegacyVpnRunner.exit();
1073 mLegacyVpnRunner = null;
1074
1075 synchronized (LegacyVpnRunner.TAG) {
1076 // wait for old thread to completely finish before spinning up
1077 // new instance, otherwise state updates can be out of order.
1078 }
1079 }
1080 }
1081
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001082 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001083 * Return the information of the current ongoing legacy VPN.
1084 */
1085 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001086 // Check if the caller is authorized.
1087 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001088 return getLegacyVpnInfoPrivileged();
1089 }
1090
1091 /**
1092 * Return the information of the current ongoing legacy VPN.
1093 * Callers are responsible for checking permissions if needed.
1094 */
1095 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001096 if (mLegacyVpnRunner == null) return null;
1097
1098 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001099 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001100 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001101 if (mNetworkInfo.isConnected()) {
1102 info.intent = mStatusIntent;
1103 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001104 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001105 }
1106
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001107 public VpnConfig getLegacyVpnConfig() {
1108 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001109 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001110 } else {
1111 return null;
1112 }
1113 }
1114
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001115 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001116 * Bringing up a VPN connection takes time, and that is all this thread
1117 * does. Here we have plenty of time. The only thing we need to take
1118 * care of is responding to interruptions as soon as possible. Otherwise
1119 * requests will be piled up. This can be done in a Handler as a state
1120 * machine, but it is much easier to read in the current form.
1121 */
1122 private class LegacyVpnRunner extends Thread {
1123 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001124
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001125 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001126 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001127 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001128 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001129 private final AtomicInteger mOuterConnection =
1130 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001131
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001132 private long mTimer = -1;
1133
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001134 /**
1135 * Watch for the outer connection (passing in the constructor) going away.
1136 */
1137 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1138 @Override
1139 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001140 if (!mEnableTeardown) return;
1141
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001142 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1143 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1144 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1145 NetworkInfo info = (NetworkInfo)intent.getExtra(
1146 ConnectivityManager.EXTRA_NETWORK_INFO);
1147 if (info != null && !info.isConnectedOrConnecting()) {
1148 try {
1149 mObserver.interfaceStatusChanged(mOuterInterface, false);
1150 } catch (RemoteException e) {}
1151 }
1152 }
1153 }
1154 }
1155 };
1156
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001157 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001158 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001159 mConfig = config;
1160 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001161 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001162 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001163 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001164
1165 // This is the interface which VPN is running on,
1166 // mConfig.interfaze will change to point to OUR
1167 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001168 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001169 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001170 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001171 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001172
Paul Jensene75b9e32015-04-06 11:54:53 -04001173 if (!TextUtils.isEmpty(mOuterInterface)) {
1174 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1175 for (Network network : cm.getAllNetworks()) {
1176 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001177 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001178 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1179 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1180 }
1181 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001182 }
1183
1184 IntentFilter filter = new IntentFilter();
1185 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1186 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001187 }
1188
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001189 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001190 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001191 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1192 exit();
1193 }
1194 }
1195
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001196 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001197 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001198 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001199 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001200 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001201 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001202 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001203 try {
1204 mContext.unregisterReceiver(mBroadcastReceiver);
1205 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001206 }
1207
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001208 @Override
1209 public void run() {
1210 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001211 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001212 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001213 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001214 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001215 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001216 }
1217 }
1218
1219 private void checkpoint(boolean yield) throws InterruptedException {
1220 long now = SystemClock.elapsedRealtime();
1221 if (mTimer == -1) {
1222 mTimer = now;
1223 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001224 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001225 Thread.sleep(yield ? 200 : 1);
1226 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001227 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001228 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 }
1230 }
1231
1232 private void execute() {
1233 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001234 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001235 try {
1236 // Initialize the timer.
1237 checkpoint(false);
1238
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001239 // Wait for the daemons to stop.
1240 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001241 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001242 checkpoint(true);
1243 }
1244 }
1245
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001246 // Clear the previous state.
1247 File state = new File("/data/misc/vpn/state");
1248 state.delete();
1249 if (state.exists()) {
1250 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001251 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001252 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001253 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001254
Chia-chi Yehe9107902011-07-02 01:48:50 -07001255 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001256 boolean restart = false;
1257 for (String[] arguments : mArguments) {
1258 restart = restart || (arguments != null);
1259 }
1260 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001261 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001262 return;
1263 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001264 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001265
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001266 // Start the daemon with arguments.
1267 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001268 String[] arguments = mArguments[i];
1269 if (arguments == null) {
1270 continue;
1271 }
1272
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001273 // Start the daemon.
1274 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001275 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001276
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001277 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001278 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001279 checkpoint(true);
1280 }
1281
1282 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001283 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001284 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001285 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001286
1287 // Wait for the socket to connect.
1288 while (true) {
1289 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001290 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001291 break;
1292 } catch (Exception e) {
1293 // ignore
1294 }
1295 checkpoint(true);
1296 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001297 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001298
1299 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001300 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001301 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001302 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001303 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001304 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001305 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001306 out.write(bytes.length >> 8);
1307 out.write(bytes.length);
1308 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001309 checkpoint(false);
1310 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001311 out.write(0xFF);
1312 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001313 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001314
1315 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001316 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001317 while (true) {
1318 try {
1319 if (in.read() == -1) {
1320 break;
1321 }
1322 } catch (Exception e) {
1323 // ignore
1324 }
1325 checkpoint(true);
1326 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001327 }
1328
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001329 // Wait for the daemons to create the new state.
1330 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001331 // Check if a running daemon is dead.
1332 for (int i = 0; i < mDaemons.length; ++i) {
1333 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001334 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001335 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001336 }
1337 }
1338 checkpoint(true);
1339 }
1340
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001341 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001342 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001343 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001344 throw new IllegalStateException("Cannot parse the state");
1345 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001346
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001347 // Set the interface and the addresses in the config.
1348 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001349
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001350 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001351 // Set the routes if they are not set in the config.
1352 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001353 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001354 }
1355
1356 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001357 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001358 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001359 if (!dnsServers.isEmpty()) {
1360 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1361 }
1362 }
1363
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001364 // Set the search domains if they are not set in the config.
1365 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1366 String searchDomains = parameters[4].trim();
1367 if (!searchDomains.isEmpty()) {
1368 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1369 }
1370 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001371
Lorenzo Colitti50262792014-09-19 01:53:35 +09001372 // Add a throw route for the VPN server endpoint, if one was specified.
1373 String endpoint = parameters[5];
1374 if (!endpoint.isEmpty()) {
1375 try {
1376 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1377 if (addr instanceof Inet4Address) {
1378 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1379 } else if (addr instanceof Inet6Address) {
1380 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1381 } else {
1382 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1383 }
1384 } catch (IllegalArgumentException e) {
1385 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1386 }
1387 }
1388
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001389 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001390 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001391 // Set the start time
1392 mConfig.startTime = SystemClock.elapsedRealtime();
1393
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001394 // Check if the thread is interrupted while we are waiting.
1395 checkpoint(false);
1396
Chia-chi Yehe9107902011-07-02 01:48:50 -07001397 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001398 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001399 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001400 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001401
1402 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001403 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001404 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001405
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001406 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001407
1408 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001409 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001410 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001411 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001412 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001413 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001414 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001415 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001416 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001417 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001418 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001419 }
1420 }
1421
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001422 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001423 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001424 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001425 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001426 }
1427 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001428
1429 /**
1430 * Monitor the daemons we started, moving to disconnected state if the
1431 * underlying services fail.
1432 */
1433 private void monitorDaemons() {
1434 if (!mNetworkInfo.isConnected()) {
1435 return;
1436 }
1437
1438 try {
1439 while (true) {
1440 Thread.sleep(2000);
1441 for (int i = 0; i < mDaemons.length; i++) {
1442 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1443 return;
1444 }
1445 }
1446 }
1447 } catch (InterruptedException e) {
1448 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1449 } finally {
1450 for (String daemon : mDaemons) {
1451 SystemService.stop(daemon);
1452 }
1453
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001454 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001455 }
1456 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001457 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001458}