blob: a07591c941104cfe26e766b31974518cb715257b [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);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400491 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700492 throw new SecurityException("Restricted users cannot establish VPNs");
493 }
494
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700495 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400496 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700497 if (info == null) {
498 throw new SecurityException("Cannot find " + config.user);
499 }
500 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
501 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
502 }
503 } catch (RemoteException e) {
504 throw new SecurityException("Cannot find " + config.user);
505 } finally {
506 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700507 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700508
Chad Brubaker850eb672014-03-21 21:02:47 +0000509 // Save the old config in case we need to go back.
510 VpnConfig oldConfig = mConfig;
511 String oldInterface = mInterface;
512 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400513 NetworkAgent oldNetworkAgent = mNetworkAgent;
514 mNetworkAgent = null;
515 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000516
Chia-chi Yehe9107902011-07-02 01:48:50 -0700517 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700518 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700519 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700520 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700521 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700522
Chad Brubakerc2865192013-07-10 14:46:23 -0700523 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700524 StringBuilder builder = new StringBuilder();
525 for (LinkAddress address : config.addresses) {
526 builder.append(" " + address);
527 }
528 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700529 throw new IllegalArgumentException("At least one address must be specified");
530 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700531 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700532 if (!mContext.bindServiceAsUser(intent, connection,
533 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
534 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700535 throw new IllegalStateException("Cannot bind " + config.user);
536 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000537
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700538 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700539 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700540
541 // Fill more values.
542 config.user = mPackage;
543 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700544 config.startTime = SystemClock.elapsedRealtime();
545 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000546
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700547 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700549
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400550 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000551
552 if (oldConnection != null) {
553 mContext.unbindService(oldConnection);
554 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400555 // Remove the old tun's user forwarding rules
556 // The new tun's user rules have already been added so they will take over
557 // as rules are deleted. This prevents data leakage as the rules are moved over.
558 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000559 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000560 jniReset(oldInterface);
561 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700562
563 try {
564 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
565 } catch (IOException e) {
566 throw new IllegalStateException(
567 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
568 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000569 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400571 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000572 // restore old state
573 mConfig = oldConfig;
574 mConnection = oldConnection;
575 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400576 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000577 mInterface = oldInterface;
578 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700579 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000580 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700581 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700582 }
583
Chad Brubakerc2865192013-07-10 14:46:23 -0700584 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800585 return mNetworkAgent != null && mInterface != null;
586 }
587
588 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
589 // that a call to mutate VPN state is admissible.
590 private boolean isCallerEstablishedOwnerLocked() {
591 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700592 }
593
Paul Jensen0784eea2014-08-19 16:00:24 -0400594 // Note: Return type guarantees results are deduped and sorted, which callers require.
595 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
596 SortedSet<Integer> uids = new TreeSet<Integer>();
597 for (String app : packageNames) {
598 int uid = getAppUid(app, userHandle);
599 if (uid != -1) uids.add(uid);
600 }
601 return uids;
602 }
603
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400604 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400605 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800606 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700607 throw new IllegalStateException("VPN is not active");
608 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700609
Paul Jensen0784eea2014-08-19 16:00:24 -0400610 if (mConfig.allowedApplications != null) {
611 // Add ranges covering all UIDs for allowedApplications.
612 int start = -1, stop = -1;
613 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
614 if (start == -1) {
615 start = uid;
616 } else if (uid != stop + 1) {
617 mVpnUsers.add(new UidRange(start, stop));
618 start = uid;
619 }
620 stop = uid;
621 }
622 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
623 } else if (mConfig.disallowedApplications != null) {
624 // Add all ranges for user skipping UIDs for disallowedApplications.
625 final UidRange userRange = UidRange.createForUser(userHandle);
626 int start = userRange.start;
627 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
628 if (uid == start) {
629 start++;
630 } else {
631 mVpnUsers.add(new UidRange(start, uid - 1));
632 start = uid + 1;
633 }
634 }
635 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
636 } else {
637 // Add all UIDs for the user.
638 mVpnUsers.add(UidRange.createForUser(userHandle));
639 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700640
641 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700642 }
643
Paul Jensen0784eea2014-08-19 16:00:24 -0400644 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
645 // apply to userHandle.
646 private List<UidRange> uidRangesForUser(int userHandle) {
647 final UidRange userRange = UidRange.createForUser(userHandle);
648 final List<UidRange> ranges = new ArrayList<UidRange>();
649 for (UidRange range : mVpnUsers) {
650 if (range.start >= userRange.start && range.stop <= userRange.stop) {
651 ranges.add(range);
652 }
653 }
654 return ranges;
655 }
656
657 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800658 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700659 throw new IllegalStateException("VPN is not active");
660 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400661 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700662 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400663 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700664 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400665 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700666 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700667 }
668
Paul Jensen0784eea2014-08-19 16:00:24 -0400669 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700670 // If the user is restricted tie them to the owner's VPN
671 synchronized(Vpn.this) {
672 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400673 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700674 if (user.isRestricted()) {
675 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400676 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400677 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400678 final List<UidRange> ranges = uidRangesForUser(userHandle);
679 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400680 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700681 } catch (Exception e) {
682 Log.wtf(TAG, "Failed to add restricted user to owner", e);
683 }
684 }
685 }
686 }
687
Paul Jensen0784eea2014-08-19 16:00:24 -0400688 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700689 // clean up if restricted
690 synchronized(Vpn.this) {
691 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400692 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700693 if (user.isRestricted()) {
694 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400695 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700696 } catch (Exception e) {
697 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
698 }
699 }
700 }
701 }
702
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700703 /**
704 * Return the configuration of the currently running VPN.
705 */
706 public VpnConfig getVpnConfig() {
707 enforceControlPermission();
708 return mConfig;
709 }
710
Jeff Sharkey899223b2012-08-04 15:24:58 -0700711 @Deprecated
712 public synchronized void interfaceStatusChanged(String iface, boolean up) {
713 try {
714 mObserver.interfaceStatusChanged(iface, up);
715 } catch (RemoteException e) {
716 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700717 }
718 }
719
Jeff Sharkey899223b2012-08-04 15:24:58 -0700720 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
721 @Override
722 public void interfaceStatusChanged(String interfaze, boolean up) {
723 synchronized (Vpn.this) {
724 if (!up && mLegacyVpnRunner != null) {
725 mLegacyVpnRunner.check(interfaze);
726 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700727 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700728 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700729
Jeff Sharkey899223b2012-08-04 15:24:58 -0700730 @Override
731 public void interfaceRemoved(String interfaze) {
732 synchronized (Vpn.this) {
733 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700734 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400735 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500736 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700737 mInterface = null;
738 if (mConnection != null) {
739 mContext.unbindService(mConnection);
740 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400741 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700742 } else if (mLegacyVpnRunner != null) {
743 mLegacyVpnRunner.exit();
744 mLegacyVpnRunner = null;
745 }
746 }
747 }
748 }
749 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700750
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700751 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800752 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700753 }
754
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700755 private class Connection implements ServiceConnection {
756 private IBinder mService;
757
758 @Override
759 public void onServiceConnected(ComponentName name, IBinder service) {
760 mService = service;
761 }
762
763 @Override
764 public void onServiceDisconnected(ComponentName name) {
765 mService = null;
766 }
767 }
768
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700769 private void prepareStatusIntent() {
770 final long token = Binder.clearCallingIdentity();
771 try {
772 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
773 } finally {
774 Binder.restoreCallingIdentity(token);
775 }
776 }
777
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700778 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800779 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700780 return false;
781 }
782 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800783 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700784 return success;
785 }
786
787 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800788 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700789 return false;
790 }
791 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800792 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700793 return success;
794 }
795
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800796 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
797 if (!isCallerEstablishedOwnerLocked()) {
798 return false;
799 }
800 if (networks == null) {
801 mConfig.underlyingNetworks = null;
802 } else {
803 mConfig.underlyingNetworks = new Network[networks.length];
804 for (int i = 0; i < networks.length; ++i) {
805 if (networks[i] == null) {
806 mConfig.underlyingNetworks[i] = null;
807 } else {
808 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
809 }
810 }
811 }
812 return true;
813 }
814
815 public synchronized Network[] getUnderlyingNetworks() {
816 if (!isRunningLocked()) {
817 return null;
818 }
819 return mConfig.underlyingNetworks;
820 }
821
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800822 /**
823 * This method should only be called by ConnectivityService. Because it doesn't
824 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
825 */
826 public synchronized VpnInfo getVpnInfo() {
827 if (!isRunningLocked()) {
828 return null;
829 }
830
831 VpnInfo info = new VpnInfo();
832 info.ownerUid = mOwnerUID;
833 info.vpnIface = mInterface;
834 return info;
835 }
836
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800837 public synchronized boolean appliesToUid(int uid) {
838 if (!isRunningLocked()) {
839 return false;
840 }
841 for (UidRange uidRange : mVpnUsers) {
842 if (uidRange.start <= uid && uid <= uidRange.stop) {
843 return true;
844 }
845 }
846 return false;
847 }
848
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700849 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700850 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700851 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700852 private native void jniReset(String interfaze);
853 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700854 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
855 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700856
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900857 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
858 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700859 // Currently legacy VPN only works on IPv4.
860 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900861 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700862 }
863 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700864
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900865 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700866 }
867
868 /**
869 * Start legacy VPN, controlling native daemons as needed. Creates a
870 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800871 *
872 * Should only be called to respond to Binder requests as this enforces caller permission. Use
873 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
874 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700875 */
876 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800877 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800878 long token = Binder.clearCallingIdentity();
879 try {
880 startLegacyVpnPrivileged(profile, keyStore, egress);
881 } finally {
882 Binder.restoreCallingIdentity(token);
883 }
884 }
885
886 /**
887 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
888 * permissions under the assumption that the caller is the system.
889 *
890 * Callers are responsible for checking permissions if needed.
891 */
892 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
893 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800894 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700895 throw new IllegalStateException("KeyStore isn't unlocked");
896 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400897 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400898 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400899 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
900 throw new SecurityException("Restricted users cannot establish VPNs");
901 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700902
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900903 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
904 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
905 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700906
907 // Load certificates.
908 String privateKey = "";
909 String userCert = "";
910 String caCert = "";
911 String serverCert = "";
912 if (!profile.ipsecUserCert.isEmpty()) {
913 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
914 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700915 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700916 }
917 if (!profile.ipsecCaCert.isEmpty()) {
918 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700919 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700920 }
921 if (!profile.ipsecServerCert.isEmpty()) {
922 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700923 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700924 }
925 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
926 throw new IllegalStateException("Cannot load credentials");
927 }
928
929 // Prepare arguments for racoon.
930 String[] racoon = null;
931 switch (profile.type) {
932 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
933 racoon = new String[] {
934 iface, profile.server, "udppsk", profile.ipsecIdentifier,
935 profile.ipsecSecret, "1701",
936 };
937 break;
938 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
939 racoon = new String[] {
940 iface, profile.server, "udprsa", privateKey, userCert,
941 caCert, serverCert, "1701",
942 };
943 break;
944 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
945 racoon = new String[] {
946 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
947 profile.ipsecSecret, profile.username, profile.password, "", gateway,
948 };
949 break;
950 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
951 racoon = new String[] {
952 iface, profile.server, "xauthrsa", privateKey, userCert,
953 caCert, serverCert, profile.username, profile.password, "", gateway,
954 };
955 break;
956 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
957 racoon = new String[] {
958 iface, profile.server, "hybridrsa",
959 caCert, serverCert, profile.username, profile.password, "", gateway,
960 };
961 break;
962 }
963
964 // Prepare arguments for mtpd.
965 String[] mtpd = null;
966 switch (profile.type) {
967 case VpnProfile.TYPE_PPTP:
968 mtpd = new String[] {
969 iface, "pptp", profile.server, "1723",
970 "name", profile.username, "password", profile.password,
971 "linkname", "vpn", "refuse-eap", "nodefaultroute",
972 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
973 (profile.mppe ? "+mppe" : "nomppe"),
974 };
975 break;
976 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
977 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
978 mtpd = new String[] {
979 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
980 "name", profile.username, "password", profile.password,
981 "linkname", "vpn", "refuse-eap", "nodefaultroute",
982 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
983 };
984 break;
985 }
986
987 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700988 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700989 config.user = profile.key;
990 config.interfaze = iface;
991 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700992
993 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700994 if (!profile.dnsServers.isEmpty()) {
995 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
996 }
997 if (!profile.searchDomains.isEmpty()) {
998 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
999 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001000 startLegacyVpn(config, racoon, mtpd);
1001 }
1002
1003 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001004 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001005
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001006 // Prepare for the new request.
1007 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001008 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001009
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001010 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001011 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1012 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001013 }
1014
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001015 /** Stop legacy VPN. Permissions must be checked by callers. */
1016 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001017 if (mLegacyVpnRunner != null) {
1018 mLegacyVpnRunner.exit();
1019 mLegacyVpnRunner = null;
1020
1021 synchronized (LegacyVpnRunner.TAG) {
1022 // wait for old thread to completely finish before spinning up
1023 // new instance, otherwise state updates can be out of order.
1024 }
1025 }
1026 }
1027
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001028 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001029 * Return the information of the current ongoing legacy VPN.
1030 */
1031 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001032 // Check if the caller is authorized.
1033 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001034 return getLegacyVpnInfoPrivileged();
1035 }
1036
1037 /**
1038 * Return the information of the current ongoing legacy VPN.
1039 * Callers are responsible for checking permissions if needed.
1040 */
1041 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001042 if (mLegacyVpnRunner == null) return null;
1043
1044 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001045 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001046 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001047 if (mNetworkInfo.isConnected()) {
1048 info.intent = mStatusIntent;
1049 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001050 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001051 }
1052
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001053 public VpnConfig getLegacyVpnConfig() {
1054 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001055 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001056 } else {
1057 return null;
1058 }
1059 }
1060
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001061 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062 * Bringing up a VPN connection takes time, and that is all this thread
1063 * does. Here we have plenty of time. The only thing we need to take
1064 * care of is responding to interruptions as soon as possible. Otherwise
1065 * requests will be piled up. This can be done in a Handler as a state
1066 * machine, but it is much easier to read in the current form.
1067 */
1068 private class LegacyVpnRunner extends Thread {
1069 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001071 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001072 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001073 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001074 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001075 private final AtomicInteger mOuterConnection =
1076 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001077
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001078 private long mTimer = -1;
1079
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001080 /**
1081 * Watch for the outer connection (passing in the constructor) going away.
1082 */
1083 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1084 @Override
1085 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001086 if (!mEnableTeardown) return;
1087
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001088 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1089 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1090 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1091 NetworkInfo info = (NetworkInfo)intent.getExtra(
1092 ConnectivityManager.EXTRA_NETWORK_INFO);
1093 if (info != null && !info.isConnectedOrConnecting()) {
1094 try {
1095 mObserver.interfaceStatusChanged(mOuterInterface, false);
1096 } catch (RemoteException e) {}
1097 }
1098 }
1099 }
1100 }
1101 };
1102
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001103 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001105 mConfig = config;
1106 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001107 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001108 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001109 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001110
1111 // This is the interface which VPN is running on,
1112 // mConfig.interfaze will change to point to OUR
1113 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001114 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001115 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001116 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001117 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001118
Paul Jensene75b9e32015-04-06 11:54:53 -04001119 if (!TextUtils.isEmpty(mOuterInterface)) {
1120 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1121 for (Network network : cm.getAllNetworks()) {
1122 final LinkProperties lp = cm.getLinkProperties(network);
1123 if (lp != null && mOuterInterface.equals(lp.getInterfaceName())) {
1124 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1125 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1126 }
1127 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001128 }
1129
1130 IntentFilter filter = new IntentFilter();
1131 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1132 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001133 }
1134
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001135 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001136 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001137 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1138 exit();
1139 }
1140 }
1141
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001142 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001143 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001144 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001145 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001146 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001147 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001148 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001149 try {
1150 mContext.unregisterReceiver(mBroadcastReceiver);
1151 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001152 }
1153
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001154 @Override
1155 public void run() {
1156 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001157 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001158 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001159 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001161 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001162 }
1163 }
1164
1165 private void checkpoint(boolean yield) throws InterruptedException {
1166 long now = SystemClock.elapsedRealtime();
1167 if (mTimer == -1) {
1168 mTimer = now;
1169 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001170 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171 Thread.sleep(yield ? 200 : 1);
1172 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001173 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001174 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001175 }
1176 }
1177
1178 private void execute() {
1179 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001180 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001181 try {
1182 // Initialize the timer.
1183 checkpoint(false);
1184
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001185 // Wait for the daemons to stop.
1186 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001187 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001188 checkpoint(true);
1189 }
1190 }
1191
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001192 // Clear the previous state.
1193 File state = new File("/data/misc/vpn/state");
1194 state.delete();
1195 if (state.exists()) {
1196 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001197 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001198 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001199 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001200
Chia-chi Yehe9107902011-07-02 01:48:50 -07001201 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001202 boolean restart = false;
1203 for (String[] arguments : mArguments) {
1204 restart = restart || (arguments != null);
1205 }
1206 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001207 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001208 return;
1209 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001210 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001211
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001212 // Start the daemon with arguments.
1213 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001214 String[] arguments = mArguments[i];
1215 if (arguments == null) {
1216 continue;
1217 }
1218
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001219 // Start the daemon.
1220 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001221 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001222
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001223 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001224 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001225 checkpoint(true);
1226 }
1227
1228 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001229 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001230 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001231 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001232
1233 // Wait for the socket to connect.
1234 while (true) {
1235 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001236 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001237 break;
1238 } catch (Exception e) {
1239 // ignore
1240 }
1241 checkpoint(true);
1242 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001243 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001244
1245 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001246 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001247 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001248 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001249 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001250 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001251 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001252 out.write(bytes.length >> 8);
1253 out.write(bytes.length);
1254 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001255 checkpoint(false);
1256 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001257 out.write(0xFF);
1258 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001259 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001260
1261 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001262 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001263 while (true) {
1264 try {
1265 if (in.read() == -1) {
1266 break;
1267 }
1268 } catch (Exception e) {
1269 // ignore
1270 }
1271 checkpoint(true);
1272 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001273 }
1274
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001275 // Wait for the daemons to create the new state.
1276 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001277 // Check if a running daemon is dead.
1278 for (int i = 0; i < mDaemons.length; ++i) {
1279 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001280 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001281 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001282 }
1283 }
1284 checkpoint(true);
1285 }
1286
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001287 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001288 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001289 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001290 throw new IllegalStateException("Cannot parse the state");
1291 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001292
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001293 // Set the interface and the addresses in the config.
1294 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001295
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001296 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001297 // Set the routes if they are not set in the config.
1298 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001299 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001300 }
1301
1302 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001303 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001304 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001305 if (!dnsServers.isEmpty()) {
1306 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1307 }
1308 }
1309
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001310 // Set the search domains if they are not set in the config.
1311 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1312 String searchDomains = parameters[4].trim();
1313 if (!searchDomains.isEmpty()) {
1314 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1315 }
1316 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001317
Lorenzo Colitti50262792014-09-19 01:53:35 +09001318 // Add a throw route for the VPN server endpoint, if one was specified.
1319 String endpoint = parameters[5];
1320 if (!endpoint.isEmpty()) {
1321 try {
1322 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1323 if (addr instanceof Inet4Address) {
1324 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1325 } else if (addr instanceof Inet6Address) {
1326 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1327 } else {
1328 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1329 }
1330 } catch (IllegalArgumentException e) {
1331 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1332 }
1333 }
1334
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001335 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001336 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001337 // Set the start time
1338 mConfig.startTime = SystemClock.elapsedRealtime();
1339
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001340 // Check if the thread is interrupted while we are waiting.
1341 checkpoint(false);
1342
Chia-chi Yehe9107902011-07-02 01:48:50 -07001343 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001344 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001345 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001346 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001347
1348 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001349 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001350 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001351
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001352 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001353
1354 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001355 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001356 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001357 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001358 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001359 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001360 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001361 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001362 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001363 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001364 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001365 }
1366 }
1367
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001368 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001369 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001370 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001371 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001372 }
1373 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001374
1375 /**
1376 * Monitor the daemons we started, moving to disconnected state if the
1377 * underlying services fail.
1378 */
1379 private void monitorDaemons() {
1380 if (!mNetworkInfo.isConnected()) {
1381 return;
1382 }
1383
1384 try {
1385 while (true) {
1386 Thread.sleep(2000);
1387 for (int i = 0; i < mDaemons.length; i++) {
1388 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1389 return;
1390 }
1391 }
1392 }
1393 } catch (InterruptedException e) {
1394 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1395 } finally {
1396 for (String daemon : mDaemons) {
1397 SystemService.stop(daemon);
1398 }
1399
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001400 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001401 }
1402 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001403 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001404}