blob: ac55292bbd3028f02c45ed44562938d7bf5008e2 [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;
Paul Jensen31a94f42015-02-13 14:18:39 -050023import static android.os.UserHandle.PER_USER_RANGE;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070024import static android.system.OsConstants.AF_INET;
25import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026
Jeff Davidsonbc19c182014-11-11 13:20:01 -080027import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070028import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070029import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070030import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070031import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070032import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.Context;
34import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070035import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040039import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070040import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070041import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070042import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070043import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070044import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090045import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070046import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070047import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070048import android.net.LocalSocket;
49import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080050import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040051import android.net.NetworkAgent;
52import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070053import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040054import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070055import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070056import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040057import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070058import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080059import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070060import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070061import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040062import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070063import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070065import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070066import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070067import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070068import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070069import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070070import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070071import android.security.Credentials;
72import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040073import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import android.util.Log;
75
Chad Brubakerc2865192013-07-10 14:46:23 -070076import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070077import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070078import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080079import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070081import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082
Jeff Davidson05542602014-08-11 14:07:27 -070083import libcore.io.IoUtils;
84
Chia-chi Yeh97a61562011-07-14 15:05:05 -070085import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070086import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070087import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070088import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070089import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070090import java.net.Inet6Address;
91import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070092import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040093import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070094import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040095import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040096import java.util.SortedSet;
97import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070098import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070099
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700100/**
101 * @hide
102 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103public class Vpn {
104 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 private static final String TAG = "Vpn";
106 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107
Jeff Sharkey899223b2012-08-04 15:24:58 -0700108 // TODO: create separate trackers for each unique VPN to support
109 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700110
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400111 private Context mContext;
112 private NetworkInfo mNetworkInfo;
113 private String mPackage;
114 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700115 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700116 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700117 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700118 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700119 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400122 private NetworkAgent mNetworkAgent;
123 private final Looper mLooper;
124 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700125
126 /* list of users using this VPN. */
127 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700129 private BroadcastReceiver mUserIntentReceiver = null;
130
Paul Jensen0784eea2014-08-19 16:00:24 -0400131 // Handle of user initiating VPN.
132 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400135 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700136 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400138 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400139 mLooper = looper;
140
141 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400142 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700143
144 try {
145 netService.registerObserver(mObserver);
146 } catch (RemoteException e) {
147 Log.wtf(TAG, "Problem registering observer", e);
148 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400149 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700150 // Owner's VPN also needs to handle restricted users
151 mUserIntentReceiver = new BroadcastReceiver() {
152 @Override
153 public void onReceive(Context context, Intent intent) {
154 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700156 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400157 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700158
159 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400160 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700161 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400162 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700163 }
164 }
165 };
166
167 IntentFilter intentFilter = new IntentFilter();
168 intentFilter.addAction(Intent.ACTION_USER_ADDED);
169 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
170 mContext.registerReceiverAsUser(
171 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
172 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173
174 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
175 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
176 mNetworkCapabilities = new NetworkCapabilities();
177 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
178 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700179 }
180
Jeff Sharkey57666932013-04-30 17:01:57 -0700181 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700182 * Set if this object is responsible for watching for {@link NetworkInfo}
183 * teardown. When {@code false}, teardown is handled externally by someone
184 * else.
185 */
186 public void setEnableTeardown(boolean enableTeardown) {
187 mEnableTeardown = enableTeardown;
188 }
189
Jeff Sharkey899223b2012-08-04 15:24:58 -0700190 /**
191 * Update current state, dispaching event to listeners.
192 */
193 private void updateState(DetailedState detailedState, String reason) {
194 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
195 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400196 if (mNetworkAgent != null) {
197 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
198 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199 }
200
201 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700202 * Prepare for a VPN application. This method is designed to solve
203 * race conditions. It first compares the current prepared package
204 * with {@code oldPackage}. If they are the same, the prepared
205 * package is revoked and replaced with {@code newPackage}. If
206 * {@code oldPackage} is {@code null}, the comparison is omitted.
207 * If {@code newPackage} is the same package or {@code null}, the
208 * revocation is omitted. This method returns {@code true} if the
209 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700210 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700211 * Legacy VPN is handled specially since it is not a real package.
212 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
213 * it can be revoked by itself.
214 *
215 * @param oldPackage The package name of the old VPN application.
216 * @param newPackage The package name of the new VPN application.
217 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700218 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700219 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidsonbe085872014-10-24 10:35:53 -0700220 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800221 // The package doesn't match. We return false (to obtain user consent) unless the user
222 // has already consented to that VPN package.
Jeff Davidson05542602014-08-11 14:07:27 -0700223 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800224 prepareInternal(oldPackage);
Jeff Davidson05542602014-08-11 14:07:27 -0700225 return true;
226 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700227 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700228 }
229
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700230 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700231 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
232 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700233 return true;
234 }
235
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700236 // Check if the caller is authorized.
237 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700238
Jeff Davidson11008a72014-11-20 13:12:46 -0800239 prepareInternal(newPackage);
240 return true;
241 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700242
Jeff Davidson11008a72014-11-20 13:12:46 -0800243 /** Prepare the VPN for the given package. Does not perform permission checks. */
244 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400245 long token = Binder.clearCallingIdentity();
246 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800247 // Reset the interface.
248 if (mInterface != null) {
249 mStatusIntent = null;
250 agentDisconnect();
251 jniReset(mInterface);
252 mInterface = null;
253 mVpnUsers = null;
254 }
255
256 // Revoke the connection or stop LegacyVpnRunner.
257 if (mConnection != null) {
258 try {
259 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
260 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
261 } catch (Exception e) {
262 // ignore
263 }
264 mContext.unbindService(mConnection);
265 mConnection = null;
266 } else if (mLegacyVpnRunner != null) {
267 mLegacyVpnRunner.exit();
268 mLegacyVpnRunner = null;
269 }
270
271 try {
272 mNetd.denyProtect(mOwnerUID);
273 } catch (Exception e) {
274 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
275 }
276
277 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
278 mPackage = newPackage;
279 mOwnerUID = getAppUid(newPackage, mUserHandle);
280 try {
281 mNetd.allowProtect(mOwnerUID);
282 } catch (Exception e) {
283 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
284 }
285 mConfig = null;
286
287 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400288 } finally {
289 Binder.restoreCallingIdentity(token);
290 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700291 }
292
Jeff Davidson05542602014-08-11 14:07:27 -0700293 /**
294 * Set whether the current package has the ability to launch VPNs without user intervention.
295 */
296 public void setPackageAuthorization(boolean authorized) {
297 // Check if the caller is authorized.
298 enforceControlPermission();
299
300 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
301 return;
302 }
303
304 long token = Binder.clearCallingIdentity();
305 try {
306 AppOpsManager appOps =
307 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
308 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
309 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
310 } catch (Exception e) {
311 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
312 } finally {
313 Binder.restoreCallingIdentity(token);
314 }
315 }
316
317 private boolean isVpnUserPreConsented(String packageName) {
318 AppOpsManager appOps =
319 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
320
321 // Verify that the caller matches the given package and has permission to activate VPNs.
322 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
323 packageName) == AppOpsManager.MODE_ALLOWED;
324 }
325
Paul Jensen0784eea2014-08-19 16:00:24 -0400326 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700327 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400328 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700329 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400330 PackageManager pm = mContext.getPackageManager();
331 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700332 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400333 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400334 } catch (NameNotFoundException e) {
335 result = -1;
336 }
337 return result;
338 }
339
340 public NetworkInfo getNetworkInfo() {
341 return mNetworkInfo;
342 }
343
Paul Jensen31a94f42015-02-13 14:18:39 -0500344 public int getNetId() {
345 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
346 }
347
Lorenzo Colitti60446162014-09-20 00:14:31 +0900348 private LinkProperties makeLinkProperties() {
349 boolean allowIPv4 = mConfig.allowIPv4;
350 boolean allowIPv6 = mConfig.allowIPv6;
351
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400352 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900353
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400354 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700355
Lorenzo Colitti60446162014-09-20 00:14:31 +0900356 if (mConfig.addresses != null) {
357 for (LinkAddress address : mConfig.addresses) {
358 lp.addLinkAddress(address);
359 allowIPv4 |= address.getAddress() instanceof Inet4Address;
360 allowIPv6 |= address.getAddress() instanceof Inet6Address;
361 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400362 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900363
364 if (mConfig.routes != null) {
365 for (RouteInfo route : mConfig.routes) {
366 lp.addRoute(route);
367 InetAddress address = route.getDestination().getAddress();
368 allowIPv4 |= address instanceof Inet4Address;
369 allowIPv6 |= address instanceof Inet6Address;
370 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400371 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700372
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400373 if (mConfig.dnsServers != null) {
374 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700375 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
376 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900377 allowIPv4 |= address instanceof Inet4Address;
378 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400379 }
380 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700381
Lorenzo Colitti60446162014-09-20 00:14:31 +0900382 if (!allowIPv4) {
383 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
384 }
385 if (!allowIPv6) {
386 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
387 }
388
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400389 // Concatenate search domains into a string.
390 StringBuilder buffer = new StringBuilder();
391 if (mConfig.searchDomains != null) {
392 for (String domain : mConfig.searchDomains) {
393 buffer.append(domain).append(' ');
394 }
395 }
396 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700397
Lorenzo Colitti60446162014-09-20 00:14:31 +0900398 // TODO: Stop setting the MTU in jniCreate and set it here.
399
400 return lp;
401 }
402
403 private void agentConnect() {
404 LinkProperties lp = makeLinkProperties();
405
406 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
407 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
408 } else {
409 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
410 }
411
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400412 mNetworkInfo.setIsAvailable(true);
413 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700414
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700415 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700416 networkMisc.allowBypass = mConfig.allowBypass;
417
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400418 long token = Binder.clearCallingIdentity();
419 try {
420 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700421 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700422 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400423 public void unwanted() {
424 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700425 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400426 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700427 } finally {
428 Binder.restoreCallingIdentity(token);
429 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700430
Paul Jensen0784eea2014-08-19 16:00:24 -0400431 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400432 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400433 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400434 token = Binder.clearCallingIdentity();
435 List<UserInfo> users;
436 try {
437 users = UserManager.get(mContext).getUsers();
438 } finally {
439 Binder.restoreCallingIdentity(token);
440 }
441 for (UserInfo user : users) {
442 if (user.isRestricted()) {
443 addVpnUserLocked(user.id);
444 }
445 }
446 }
447 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
448 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700449
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400450 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
451 networkInfo.setIsAvailable(false);
452 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
453 if (networkAgent != null) {
454 networkAgent.sendNetworkInfo(networkInfo);
455 }
456 }
457
458 private void agentDisconnect(NetworkAgent networkAgent) {
459 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
460 agentDisconnect(networkInfo, networkAgent);
461 }
462
463 private void agentDisconnect() {
464 if (mNetworkInfo.isConnected()) {
465 agentDisconnect(mNetworkInfo, mNetworkAgent);
466 mNetworkAgent = null;
467 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700468 }
469
470 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700471 * Establish a VPN network and return the file descriptor of the VPN
472 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700473 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700474 *
475 * @param config The parameters to configure the network.
476 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700477 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700478 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700479 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700480 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400481 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700482 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700483 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700484 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700485 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
486 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700487 long token = Binder.clearCallingIdentity();
488 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700489 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400490 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000491 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
492 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700493 throw new SecurityException("Restricted users cannot establish VPNs");
494 }
495
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700496 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400497 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700498 if (info == null) {
499 throw new SecurityException("Cannot find " + config.user);
500 }
501 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
502 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
503 }
504 } catch (RemoteException e) {
505 throw new SecurityException("Cannot find " + config.user);
506 } finally {
507 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700508 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700509
Chad Brubaker850eb672014-03-21 21:02:47 +0000510 // Save the old config in case we need to go back.
511 VpnConfig oldConfig = mConfig;
512 String oldInterface = mInterface;
513 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400514 NetworkAgent oldNetworkAgent = mNetworkAgent;
515 mNetworkAgent = null;
516 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000517
Chia-chi Yehe9107902011-07-02 01:48:50 -0700518 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700519 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700520 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700521 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700522 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700523
Chad Brubakerc2865192013-07-10 14:46:23 -0700524 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700525 StringBuilder builder = new StringBuilder();
526 for (LinkAddress address : config.addresses) {
527 builder.append(" " + address);
528 }
529 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700530 throw new IllegalArgumentException("At least one address must be specified");
531 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700532 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700533 if (!mContext.bindServiceAsUser(intent, connection,
534 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
535 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700536 throw new IllegalStateException("Cannot bind " + config.user);
537 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000538
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700539 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700540 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700541
542 // Fill more values.
543 config.user = mPackage;
544 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700545 config.startTime = SystemClock.elapsedRealtime();
546 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000547
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700548 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400549 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700550
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400551 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000552
553 if (oldConnection != null) {
554 mContext.unbindService(oldConnection);
555 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400556 // Remove the old tun's user forwarding rules
557 // The new tun's user rules have already been added so they will take over
558 // as rules are deleted. This prevents data leakage as the rules are moved over.
559 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000560 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000561 jniReset(oldInterface);
562 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700563
564 try {
565 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
566 } catch (IOException e) {
567 throw new IllegalStateException(
568 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
569 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000571 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400572 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000573 // restore old state
574 mConfig = oldConfig;
575 mConnection = oldConnection;
576 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400577 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000578 mInterface = oldInterface;
579 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700580 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000581 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700582 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700583 }
584
Chad Brubakerc2865192013-07-10 14:46:23 -0700585 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800586 return mNetworkAgent != null && mInterface != null;
587 }
588
589 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
590 // that a call to mutate VPN state is admissible.
591 private boolean isCallerEstablishedOwnerLocked() {
592 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700593 }
594
Paul Jensen0784eea2014-08-19 16:00:24 -0400595 // Note: Return type guarantees results are deduped and sorted, which callers require.
596 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
597 SortedSet<Integer> uids = new TreeSet<Integer>();
598 for (String app : packageNames) {
599 int uid = getAppUid(app, userHandle);
600 if (uid != -1) uids.add(uid);
601 }
602 return uids;
603 }
604
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400605 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400606 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800607 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700608 throw new IllegalStateException("VPN is not active");
609 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700610
Paul Jensen0784eea2014-08-19 16:00:24 -0400611 if (mConfig.allowedApplications != null) {
612 // Add ranges covering all UIDs for allowedApplications.
613 int start = -1, stop = -1;
614 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
615 if (start == -1) {
616 start = uid;
617 } else if (uid != stop + 1) {
618 mVpnUsers.add(new UidRange(start, stop));
619 start = uid;
620 }
621 stop = uid;
622 }
623 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
624 } else if (mConfig.disallowedApplications != null) {
625 // Add all ranges for user skipping UIDs for disallowedApplications.
626 final UidRange userRange = UidRange.createForUser(userHandle);
627 int start = userRange.start;
628 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
629 if (uid == start) {
630 start++;
631 } else {
632 mVpnUsers.add(new UidRange(start, uid - 1));
633 start = uid + 1;
634 }
635 }
636 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
637 } else {
638 // Add all UIDs for the user.
639 mVpnUsers.add(UidRange.createForUser(userHandle));
640 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700641
642 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700643 }
644
Paul Jensen0784eea2014-08-19 16:00:24 -0400645 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
646 // apply to userHandle.
647 private List<UidRange> uidRangesForUser(int userHandle) {
648 final UidRange userRange = UidRange.createForUser(userHandle);
649 final List<UidRange> ranges = new ArrayList<UidRange>();
650 for (UidRange range : mVpnUsers) {
651 if (range.start >= userRange.start && range.stop <= userRange.stop) {
652 ranges.add(range);
653 }
654 }
655 return ranges;
656 }
657
658 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800659 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700660 throw new IllegalStateException("VPN is not active");
661 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400662 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700663 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400664 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700665 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400666 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700667 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700668 }
669
Paul Jensen0784eea2014-08-19 16:00:24 -0400670 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700671 // If the user is restricted tie them to the owner's VPN
672 synchronized(Vpn.this) {
673 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400674 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700675 if (user.isRestricted()) {
676 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400677 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400678 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400679 final List<UidRange> ranges = uidRangesForUser(userHandle);
680 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400681 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700682 } catch (Exception e) {
683 Log.wtf(TAG, "Failed to add restricted user to owner", e);
684 }
685 }
686 }
687 }
688
Paul Jensen0784eea2014-08-19 16:00:24 -0400689 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700690 // clean up if restricted
691 synchronized(Vpn.this) {
692 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400693 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700694 if (user.isRestricted()) {
695 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400696 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700697 } catch (Exception e) {
698 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
699 }
700 }
701 }
702 }
703
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700704 /**
705 * Return the configuration of the currently running VPN.
706 */
707 public VpnConfig getVpnConfig() {
708 enforceControlPermission();
709 return mConfig;
710 }
711
Jeff Sharkey899223b2012-08-04 15:24:58 -0700712 @Deprecated
713 public synchronized void interfaceStatusChanged(String iface, boolean up) {
714 try {
715 mObserver.interfaceStatusChanged(iface, up);
716 } catch (RemoteException e) {
717 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700718 }
719 }
720
Jeff Sharkey899223b2012-08-04 15:24:58 -0700721 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
722 @Override
723 public void interfaceStatusChanged(String interfaze, boolean up) {
724 synchronized (Vpn.this) {
725 if (!up && mLegacyVpnRunner != null) {
726 mLegacyVpnRunner.check(interfaze);
727 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700728 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700729 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700730
Jeff Sharkey899223b2012-08-04 15:24:58 -0700731 @Override
732 public void interfaceRemoved(String interfaze) {
733 synchronized (Vpn.this) {
734 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700735 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400736 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500737 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700738 mInterface = null;
739 if (mConnection != null) {
740 mContext.unbindService(mConnection);
741 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400742 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700743 } else if (mLegacyVpnRunner != null) {
744 mLegacyVpnRunner.exit();
745 mLegacyVpnRunner = null;
746 }
747 }
748 }
749 }
750 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700751
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700752 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800753 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700754 }
755
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700756 private class Connection implements ServiceConnection {
757 private IBinder mService;
758
759 @Override
760 public void onServiceConnected(ComponentName name, IBinder service) {
761 mService = service;
762 }
763
764 @Override
765 public void onServiceDisconnected(ComponentName name) {
766 mService = null;
767 }
768 }
769
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700770 private void prepareStatusIntent() {
771 final long token = Binder.clearCallingIdentity();
772 try {
773 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
774 } finally {
775 Binder.restoreCallingIdentity(token);
776 }
777 }
778
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700779 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800780 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700781 return false;
782 }
783 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800784 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700785 return success;
786 }
787
788 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800789 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700790 return false;
791 }
792 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800793 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700794 return success;
795 }
796
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800797 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
798 if (!isCallerEstablishedOwnerLocked()) {
799 return false;
800 }
801 if (networks == null) {
802 mConfig.underlyingNetworks = null;
803 } else {
804 mConfig.underlyingNetworks = new Network[networks.length];
805 for (int i = 0; i < networks.length; ++i) {
806 if (networks[i] == null) {
807 mConfig.underlyingNetworks[i] = null;
808 } else {
809 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
810 }
811 }
812 }
813 return true;
814 }
815
816 public synchronized Network[] getUnderlyingNetworks() {
817 if (!isRunningLocked()) {
818 return null;
819 }
820 return mConfig.underlyingNetworks;
821 }
822
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800823 /**
824 * This method should only be called by ConnectivityService. Because it doesn't
825 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
826 */
827 public synchronized VpnInfo getVpnInfo() {
828 if (!isRunningLocked()) {
829 return null;
830 }
831
832 VpnInfo info = new VpnInfo();
833 info.ownerUid = mOwnerUID;
834 info.vpnIface = mInterface;
835 return info;
836 }
837
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800838 public synchronized boolean appliesToUid(int uid) {
839 if (!isRunningLocked()) {
840 return false;
841 }
842 for (UidRange uidRange : mVpnUsers) {
843 if (uidRange.start <= uid && uid <= uidRange.stop) {
844 return true;
845 }
846 }
847 return false;
848 }
849
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700850 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700851 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700852 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700853 private native void jniReset(String interfaze);
854 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700855 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
856 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700857
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900858 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
859 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700860 // Currently legacy VPN only works on IPv4.
861 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900862 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700863 }
864 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700865
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900866 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700867 }
868
869 /**
870 * Start legacy VPN, controlling native daemons as needed. Creates a
871 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800872 *
873 * Should only be called to respond to Binder requests as this enforces caller permission. Use
874 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
875 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700876 */
877 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800878 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800879 long token = Binder.clearCallingIdentity();
880 try {
881 startLegacyVpnPrivileged(profile, keyStore, egress);
882 } finally {
883 Binder.restoreCallingIdentity(token);
884 }
885 }
886
887 /**
888 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
889 * permissions under the assumption that the caller is the system.
890 *
891 * Callers are responsible for checking permissions if needed.
892 */
893 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
894 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800895 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700896 throw new IllegalStateException("KeyStore isn't unlocked");
897 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400898 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400899 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000900 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
901 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400902 throw new SecurityException("Restricted users cannot establish VPNs");
903 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700904
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900905 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
906 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
907 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700908
909 // Load certificates.
910 String privateKey = "";
911 String userCert = "";
912 String caCert = "";
913 String serverCert = "";
914 if (!profile.ipsecUserCert.isEmpty()) {
915 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
916 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700917 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700918 }
919 if (!profile.ipsecCaCert.isEmpty()) {
920 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700921 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700922 }
923 if (!profile.ipsecServerCert.isEmpty()) {
924 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700925 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700926 }
927 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
928 throw new IllegalStateException("Cannot load credentials");
929 }
930
931 // Prepare arguments for racoon.
932 String[] racoon = null;
933 switch (profile.type) {
934 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
935 racoon = new String[] {
936 iface, profile.server, "udppsk", profile.ipsecIdentifier,
937 profile.ipsecSecret, "1701",
938 };
939 break;
940 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
941 racoon = new String[] {
942 iface, profile.server, "udprsa", privateKey, userCert,
943 caCert, serverCert, "1701",
944 };
945 break;
946 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
947 racoon = new String[] {
948 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
949 profile.ipsecSecret, profile.username, profile.password, "", gateway,
950 };
951 break;
952 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
953 racoon = new String[] {
954 iface, profile.server, "xauthrsa", privateKey, userCert,
955 caCert, serverCert, profile.username, profile.password, "", gateway,
956 };
957 break;
958 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
959 racoon = new String[] {
960 iface, profile.server, "hybridrsa",
961 caCert, serverCert, profile.username, profile.password, "", gateway,
962 };
963 break;
964 }
965
966 // Prepare arguments for mtpd.
967 String[] mtpd = null;
968 switch (profile.type) {
969 case VpnProfile.TYPE_PPTP:
970 mtpd = new String[] {
971 iface, "pptp", profile.server, "1723",
972 "name", profile.username, "password", profile.password,
973 "linkname", "vpn", "refuse-eap", "nodefaultroute",
974 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
975 (profile.mppe ? "+mppe" : "nomppe"),
976 };
977 break;
978 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
979 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
980 mtpd = new String[] {
981 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
982 "name", profile.username, "password", profile.password,
983 "linkname", "vpn", "refuse-eap", "nodefaultroute",
984 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
985 };
986 break;
987 }
988
989 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700990 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700991 config.user = profile.key;
992 config.interfaze = iface;
993 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700994
995 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700996 if (!profile.dnsServers.isEmpty()) {
997 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
998 }
999 if (!profile.searchDomains.isEmpty()) {
1000 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1001 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001002 startLegacyVpn(config, racoon, mtpd);
1003 }
1004
1005 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001006 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001007
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001008 // Prepare for the new request.
1009 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001010 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001011
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001012 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001013 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1014 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001015 }
1016
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001017 /** Stop legacy VPN. Permissions must be checked by callers. */
1018 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001019 if (mLegacyVpnRunner != null) {
1020 mLegacyVpnRunner.exit();
1021 mLegacyVpnRunner = null;
1022
1023 synchronized (LegacyVpnRunner.TAG) {
1024 // wait for old thread to completely finish before spinning up
1025 // new instance, otherwise state updates can be out of order.
1026 }
1027 }
1028 }
1029
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001030 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001031 * Return the information of the current ongoing legacy VPN.
1032 */
1033 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001034 // Check if the caller is authorized.
1035 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001036 return getLegacyVpnInfoPrivileged();
1037 }
1038
1039 /**
1040 * Return the information of the current ongoing legacy VPN.
1041 * Callers are responsible for checking permissions if needed.
1042 */
1043 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001044 if (mLegacyVpnRunner == null) return null;
1045
1046 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001047 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001048 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001049 if (mNetworkInfo.isConnected()) {
1050 info.intent = mStatusIntent;
1051 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001052 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001053 }
1054
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001055 public VpnConfig getLegacyVpnConfig() {
1056 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001057 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001058 } else {
1059 return null;
1060 }
1061 }
1062
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001063 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001064 * Bringing up a VPN connection takes time, and that is all this thread
1065 * does. Here we have plenty of time. The only thing we need to take
1066 * care of is responding to interruptions as soon as possible. Otherwise
1067 * requests will be piled up. This can be done in a Handler as a state
1068 * machine, but it is much easier to read in the current form.
1069 */
1070 private class LegacyVpnRunner extends Thread {
1071 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001072
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001073 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001074 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001075 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001076 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001077 private final AtomicInteger mOuterConnection =
1078 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001079
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001080 private long mTimer = -1;
1081
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001082 /**
1083 * Watch for the outer connection (passing in the constructor) going away.
1084 */
1085 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1086 @Override
1087 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001088 if (!mEnableTeardown) return;
1089
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001090 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1091 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1092 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1093 NetworkInfo info = (NetworkInfo)intent.getExtra(
1094 ConnectivityManager.EXTRA_NETWORK_INFO);
1095 if (info != null && !info.isConnectedOrConnecting()) {
1096 try {
1097 mObserver.interfaceStatusChanged(mOuterInterface, false);
1098 } catch (RemoteException e) {}
1099 }
1100 }
1101 }
1102 }
1103 };
1104
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001105 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001106 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001107 mConfig = config;
1108 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001109 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001110 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001111 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001112
1113 // This is the interface which VPN is running on,
1114 // mConfig.interfaze will change to point to OUR
1115 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001116 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001117 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001118 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001119 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001120
Paul Jensene75b9e32015-04-06 11:54:53 -04001121 if (!TextUtils.isEmpty(mOuterInterface)) {
1122 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1123 for (Network network : cm.getAllNetworks()) {
1124 final LinkProperties lp = cm.getLinkProperties(network);
1125 if (lp != null && mOuterInterface.equals(lp.getInterfaceName())) {
1126 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1127 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1128 }
1129 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001130 }
1131
1132 IntentFilter filter = new IntentFilter();
1133 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1134 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001135 }
1136
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001137 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001138 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001139 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1140 exit();
1141 }
1142 }
1143
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001144 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001145 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001146 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001147 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001148 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001149 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001150 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001151 try {
1152 mContext.unregisterReceiver(mBroadcastReceiver);
1153 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001154 }
1155
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001156 @Override
1157 public void run() {
1158 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001159 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001161 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001162 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001163 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001164 }
1165 }
1166
1167 private void checkpoint(boolean yield) throws InterruptedException {
1168 long now = SystemClock.elapsedRealtime();
1169 if (mTimer == -1) {
1170 mTimer = now;
1171 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001172 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001173 Thread.sleep(yield ? 200 : 1);
1174 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001175 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001176 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001177 }
1178 }
1179
1180 private void execute() {
1181 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001182 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 try {
1184 // Initialize the timer.
1185 checkpoint(false);
1186
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001187 // Wait for the daemons to stop.
1188 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001189 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001190 checkpoint(true);
1191 }
1192 }
1193
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001194 // Clear the previous state.
1195 File state = new File("/data/misc/vpn/state");
1196 state.delete();
1197 if (state.exists()) {
1198 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001199 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001200 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001201 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001202
Chia-chi Yehe9107902011-07-02 01:48:50 -07001203 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001204 boolean restart = false;
1205 for (String[] arguments : mArguments) {
1206 restart = restart || (arguments != null);
1207 }
1208 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001209 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001210 return;
1211 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001212 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001213
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001214 // Start the daemon with arguments.
1215 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001216 String[] arguments = mArguments[i];
1217 if (arguments == null) {
1218 continue;
1219 }
1220
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001221 // Start the daemon.
1222 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001223 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001224
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001225 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001226 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001227 checkpoint(true);
1228 }
1229
1230 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001231 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001232 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001233 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001234
1235 // Wait for the socket to connect.
1236 while (true) {
1237 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001238 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001239 break;
1240 } catch (Exception e) {
1241 // ignore
1242 }
1243 checkpoint(true);
1244 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001245 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001246
1247 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001248 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001249 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001250 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001251 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001252 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001253 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001254 out.write(bytes.length >> 8);
1255 out.write(bytes.length);
1256 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001257 checkpoint(false);
1258 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001259 out.write(0xFF);
1260 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001261 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001262
1263 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001264 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001265 while (true) {
1266 try {
1267 if (in.read() == -1) {
1268 break;
1269 }
1270 } catch (Exception e) {
1271 // ignore
1272 }
1273 checkpoint(true);
1274 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001275 }
1276
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001277 // Wait for the daemons to create the new state.
1278 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001279 // Check if a running daemon is dead.
1280 for (int i = 0; i < mDaemons.length; ++i) {
1281 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001282 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001283 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001284 }
1285 }
1286 checkpoint(true);
1287 }
1288
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001289 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001290 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001291 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001292 throw new IllegalStateException("Cannot parse the state");
1293 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001294
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001295 // Set the interface and the addresses in the config.
1296 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001297
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001298 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001299 // Set the routes if they are not set in the config.
1300 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001301 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001302 }
1303
1304 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001305 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001306 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001307 if (!dnsServers.isEmpty()) {
1308 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1309 }
1310 }
1311
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001312 // Set the search domains if they are not set in the config.
1313 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1314 String searchDomains = parameters[4].trim();
1315 if (!searchDomains.isEmpty()) {
1316 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1317 }
1318 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001319
Lorenzo Colitti50262792014-09-19 01:53:35 +09001320 // Add a throw route for the VPN server endpoint, if one was specified.
1321 String endpoint = parameters[5];
1322 if (!endpoint.isEmpty()) {
1323 try {
1324 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1325 if (addr instanceof Inet4Address) {
1326 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1327 } else if (addr instanceof Inet6Address) {
1328 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1329 } else {
1330 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1331 }
1332 } catch (IllegalArgumentException e) {
1333 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1334 }
1335 }
1336
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001337 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001338 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001339 // Set the start time
1340 mConfig.startTime = SystemClock.elapsedRealtime();
1341
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001342 // Check if the thread is interrupted while we are waiting.
1343 checkpoint(false);
1344
Chia-chi Yehe9107902011-07-02 01:48:50 -07001345 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001346 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001347 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001348 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001349
1350 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001351 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001352 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001353
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001354 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001355
1356 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001357 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001358 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001359 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001360 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001361 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001362 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001363 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001364 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001365 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001366 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001367 }
1368 }
1369
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001370 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001371 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001372 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001373 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001374 }
1375 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001376
1377 /**
1378 * Monitor the daemons we started, moving to disconnected state if the
1379 * underlying services fail.
1380 */
1381 private void monitorDaemons() {
1382 if (!mNetworkInfo.isConnected()) {
1383 return;
1384 }
1385
1386 try {
1387 while (true) {
1388 Thread.sleep(2000);
1389 for (int i = 0; i < mDaemons.length; i++) {
1390 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1391 return;
1392 }
1393 }
1394 }
1395 } catch (InterruptedException e) {
1396 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1397 } finally {
1398 for (String daemon : mDaemons) {
1399 SystemService.stop(daemon);
1400 }
1401
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001402 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001403 }
1404 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001405 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001406}