blob: bd0e58768ae5aafee62be91a98ed16c46d0c22aa [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 Jensen0784eea2014-08-19 16:00:24 -040020import static android.os.UserHandle.PER_USER_RANGE;
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;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070023import static android.system.OsConstants.AF_INET;
24import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070025
Jeff Davidsonbc19c182014-11-11 13:20:01 -080026import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070027import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070028import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070029import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070030import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070031import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070032import android.content.Context;
33import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070034import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070035import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040038import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070039import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070040import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070041import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070042import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070043import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090044import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070045import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070046import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070047import android.net.LocalSocket;
48import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080049import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040050import android.net.NetworkAgent;
51import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070052import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040053import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070054import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070055import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040056import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070057import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080058import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070059import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070060import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040061import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070062import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070063import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070064import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070065import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070066import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070067import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070068import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070069import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070070import android.security.Credentials;
71import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070072import android.util.Log;
73
Chad Brubakerc2865192013-07-10 14:46:23 -070074import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070075import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070076import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070077import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070078import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070079
Jeff Davidson05542602014-08-11 14:07:27 -070080import libcore.io.IoUtils;
81
Chia-chi Yeh97a61562011-07-14 15:05:05 -070082import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070083import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070084import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070085import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070086import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070087import java.net.Inet6Address;
88import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070089import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040090import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070091import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040092import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040093import java.util.SortedSet;
94import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070095import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070096
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070097/**
98 * @hide
99 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100public class Vpn {
101 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700102 private static final String TAG = "Vpn";
103 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 // TODO: create separate trackers for each unique VPN to support
106 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700107
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400108 private Context mContext;
109 private NetworkInfo mNetworkInfo;
110 private String mPackage;
111 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700112 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700113 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700114 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700115 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700116 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700117 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400118 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700119 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120 private NetworkAgent mNetworkAgent;
121 private final Looper mLooper;
122 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700123
124 /* list of users using this VPN. */
125 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400126 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700127 private BroadcastReceiver mUserIntentReceiver = null;
128
Paul Jensen0784eea2014-08-19 16:00:24 -0400129 // Handle of user initiating VPN.
130 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400133 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700134 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400135 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700136 mConnService = connService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400137 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400138 mLooper = looper;
139
140 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400141 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700142
143 try {
144 netService.registerObserver(mObserver);
145 } catch (RemoteException e) {
146 Log.wtf(TAG, "Problem registering observer", e);
147 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400148 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700149 // Owner's VPN also needs to handle restricted users
150 mUserIntentReceiver = new BroadcastReceiver() {
151 @Override
152 public void onReceive(Context context, Intent intent) {
153 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400154 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700155 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400156 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700157
158 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400159 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700160 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400161 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700162 }
163 }
164 };
165
166 IntentFilter intentFilter = new IntentFilter();
167 intentFilter.addAction(Intent.ACTION_USER_ADDED);
168 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
169 mContext.registerReceiverAsUser(
170 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
171 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400172
173 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
174 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
175 mNetworkCapabilities = new NetworkCapabilities();
176 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
177 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700178 }
179
Jeff Sharkey57666932013-04-30 17:01:57 -0700180 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700181 * Set if this object is responsible for watching for {@link NetworkInfo}
182 * teardown. When {@code false}, teardown is handled externally by someone
183 * else.
184 */
185 public void setEnableTeardown(boolean enableTeardown) {
186 mEnableTeardown = enableTeardown;
187 }
188
Jeff Sharkey899223b2012-08-04 15:24:58 -0700189 /**
190 * Update current state, dispaching event to listeners.
191 */
192 private void updateState(DetailedState detailedState, String reason) {
193 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
194 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400195 if (mNetworkAgent != null) {
196 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
197 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700198 }
199
200 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700201 * Prepare for a VPN application. This method is designed to solve
202 * race conditions. It first compares the current prepared package
203 * with {@code oldPackage}. If they are the same, the prepared
204 * package is revoked and replaced with {@code newPackage}. If
205 * {@code oldPackage} is {@code null}, the comparison is omitted.
206 * If {@code newPackage} is the same package or {@code null}, the
207 * revocation is omitted. This method returns {@code true} if the
208 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700209 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700210 * Legacy VPN is handled specially since it is not a real package.
211 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
212 * it can be revoked by itself.
213 *
214 * @param oldPackage The package name of the old VPN application.
215 * @param newPackage The package name of the new VPN application.
216 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700217 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700218 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidsonbe085872014-10-24 10:35:53 -0700219 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800220 // The package doesn't match. We return false (to obtain user consent) unless the user
221 // has already consented to that VPN package.
Jeff Davidson05542602014-08-11 14:07:27 -0700222 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800223 prepareInternal(oldPackage);
Jeff Davidson05542602014-08-11 14:07:27 -0700224 return true;
225 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700226 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700227 }
228
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700229 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700230 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
231 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700232 return true;
233 }
234
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700235 // Check if the caller is authorized.
236 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700237
Jeff Davidson11008a72014-11-20 13:12:46 -0800238 prepareInternal(newPackage);
239 return true;
240 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700241
Jeff Davidson11008a72014-11-20 13:12:46 -0800242 /** Prepare the VPN for the given package. Does not perform permission checks. */
243 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400244 long token = Binder.clearCallingIdentity();
245 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800246 // Reset the interface.
247 if (mInterface != null) {
248 mStatusIntent = null;
249 agentDisconnect();
250 jniReset(mInterface);
251 mInterface = null;
252 mVpnUsers = null;
253 }
254
255 // Revoke the connection or stop LegacyVpnRunner.
256 if (mConnection != null) {
257 try {
258 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
259 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
260 } catch (Exception e) {
261 // ignore
262 }
263 mContext.unbindService(mConnection);
264 mConnection = null;
265 } else if (mLegacyVpnRunner != null) {
266 mLegacyVpnRunner.exit();
267 mLegacyVpnRunner = null;
268 }
269
270 try {
271 mNetd.denyProtect(mOwnerUID);
272 } catch (Exception e) {
273 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
274 }
275
276 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
277 mPackage = newPackage;
278 mOwnerUID = getAppUid(newPackage, mUserHandle);
279 try {
280 mNetd.allowProtect(mOwnerUID);
281 } catch (Exception e) {
282 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
283 }
284 mConfig = null;
285
286 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400287 } finally {
288 Binder.restoreCallingIdentity(token);
289 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700290 }
291
Jeff Davidson05542602014-08-11 14:07:27 -0700292 /**
293 * Set whether the current package has the ability to launch VPNs without user intervention.
294 */
295 public void setPackageAuthorization(boolean authorized) {
296 // Check if the caller is authorized.
297 enforceControlPermission();
298
299 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
300 return;
301 }
302
303 long token = Binder.clearCallingIdentity();
304 try {
305 AppOpsManager appOps =
306 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
307 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
308 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
309 } catch (Exception e) {
310 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
311 } finally {
312 Binder.restoreCallingIdentity(token);
313 }
314 }
315
316 private boolean isVpnUserPreConsented(String packageName) {
317 AppOpsManager appOps =
318 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
319
320 // Verify that the caller matches the given package and has permission to activate VPNs.
321 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
322 packageName) == AppOpsManager.MODE_ALLOWED;
323 }
324
Paul Jensen0784eea2014-08-19 16:00:24 -0400325 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700326 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400327 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700328 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400329 PackageManager pm = mContext.getPackageManager();
330 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700331 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400332 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400333 } catch (NameNotFoundException e) {
334 result = -1;
335 }
336 return result;
337 }
338
339 public NetworkInfo getNetworkInfo() {
340 return mNetworkInfo;
341 }
342
Lorenzo Colitti60446162014-09-20 00:14:31 +0900343 private LinkProperties makeLinkProperties() {
344 boolean allowIPv4 = mConfig.allowIPv4;
345 boolean allowIPv6 = mConfig.allowIPv6;
346
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400347 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900348
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400349 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700350
Lorenzo Colitti60446162014-09-20 00:14:31 +0900351 if (mConfig.addresses != null) {
352 for (LinkAddress address : mConfig.addresses) {
353 lp.addLinkAddress(address);
354 allowIPv4 |= address.getAddress() instanceof Inet4Address;
355 allowIPv6 |= address.getAddress() instanceof Inet6Address;
356 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400357 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900358
359 if (mConfig.routes != null) {
360 for (RouteInfo route : mConfig.routes) {
361 lp.addRoute(route);
362 InetAddress address = route.getDestination().getAddress();
363 allowIPv4 |= address instanceof Inet4Address;
364 allowIPv6 |= address instanceof Inet6Address;
365 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400366 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700367
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 if (mConfig.dnsServers != null) {
369 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700370 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
371 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900372 allowIPv4 |= address instanceof Inet4Address;
373 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400374 }
375 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700376
Lorenzo Colitti60446162014-09-20 00:14:31 +0900377 if (!allowIPv4) {
378 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
379 }
380 if (!allowIPv6) {
381 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
382 }
383
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400384 // Concatenate search domains into a string.
385 StringBuilder buffer = new StringBuilder();
386 if (mConfig.searchDomains != null) {
387 for (String domain : mConfig.searchDomains) {
388 buffer.append(domain).append(' ');
389 }
390 }
391 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700392
Lorenzo Colitti60446162014-09-20 00:14:31 +0900393 // TODO: Stop setting the MTU in jniCreate and set it here.
394
395 return lp;
396 }
397
398 private void agentConnect() {
399 LinkProperties lp = makeLinkProperties();
400
401 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
402 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
403 } else {
404 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
405 }
406
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400407 mNetworkInfo.setIsAvailable(true);
408 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700409
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700410 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700411 networkMisc.allowBypass = mConfig.allowBypass;
412
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400413 long token = Binder.clearCallingIdentity();
414 try {
415 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700416 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700417 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400418 public void unwanted() {
419 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700420 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400421 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700422 } finally {
423 Binder.restoreCallingIdentity(token);
424 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700425
Paul Jensen0784eea2014-08-19 16:00:24 -0400426 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400427 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400428 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400429 token = Binder.clearCallingIdentity();
430 List<UserInfo> users;
431 try {
432 users = UserManager.get(mContext).getUsers();
433 } finally {
434 Binder.restoreCallingIdentity(token);
435 }
436 for (UserInfo user : users) {
437 if (user.isRestricted()) {
438 addVpnUserLocked(user.id);
439 }
440 }
441 }
442 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
443 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700444
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400445 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
446 networkInfo.setIsAvailable(false);
447 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
448 if (networkAgent != null) {
449 networkAgent.sendNetworkInfo(networkInfo);
450 }
451 }
452
453 private void agentDisconnect(NetworkAgent networkAgent) {
454 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
455 agentDisconnect(networkInfo, networkAgent);
456 }
457
458 private void agentDisconnect() {
459 if (mNetworkInfo.isConnected()) {
460 agentDisconnect(mNetworkInfo, mNetworkAgent);
461 mNetworkAgent = null;
462 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700463 }
464
465 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700466 * Establish a VPN network and return the file descriptor of the VPN
467 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700468 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700469 *
470 * @param config The parameters to configure the network.
471 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700472 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700473 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700474 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700475 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400476 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700477 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700478 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700479 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700480 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
481 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700482 long token = Binder.clearCallingIdentity();
483 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700484 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400485 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400486 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700487 throw new SecurityException("Restricted users cannot establish VPNs");
488 }
489
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700490 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400491 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700492 if (info == null) {
493 throw new SecurityException("Cannot find " + config.user);
494 }
495 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
496 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
497 }
498 } catch (RemoteException e) {
499 throw new SecurityException("Cannot find " + config.user);
500 } finally {
501 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700502 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700503
Chad Brubaker850eb672014-03-21 21:02:47 +0000504 // Save the old config in case we need to go back.
505 VpnConfig oldConfig = mConfig;
506 String oldInterface = mInterface;
507 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400508 NetworkAgent oldNetworkAgent = mNetworkAgent;
509 mNetworkAgent = null;
510 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000511
Chia-chi Yehe9107902011-07-02 01:48:50 -0700512 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700513 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700514 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700515 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700516 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700517
Chad Brubakerc2865192013-07-10 14:46:23 -0700518 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700519 StringBuilder builder = new StringBuilder();
520 for (LinkAddress address : config.addresses) {
521 builder.append(" " + address);
522 }
523 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700524 throw new IllegalArgumentException("At least one address must be specified");
525 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700526 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700527 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400528 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700529 throw new IllegalStateException("Cannot bind " + config.user);
530 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000531
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700532 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700533 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700534
535 // Fill more values.
536 config.user = mPackage;
537 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700538 config.startTime = SystemClock.elapsedRealtime();
539 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000540
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700541 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400542 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700543
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400544 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000545
546 if (oldConnection != null) {
547 mContext.unbindService(oldConnection);
548 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400549 // Remove the old tun's user forwarding rules
550 // The new tun's user rules have already been added so they will take over
551 // as rules are deleted. This prevents data leakage as the rules are moved over.
552 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000553 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000554 jniReset(oldInterface);
555 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700556
557 try {
558 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
559 } catch (IOException e) {
560 throw new IllegalStateException(
561 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
562 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000564 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400565 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000566 // restore old state
567 mConfig = oldConfig;
568 mConnection = oldConnection;
569 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400570 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000571 mInterface = oldInterface;
572 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700573 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000574 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700575 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700576 }
577
Chad Brubakerc2865192013-07-10 14:46:23 -0700578 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800579 return mNetworkAgent != null && mInterface != null;
580 }
581
582 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
583 // that a call to mutate VPN state is admissible.
584 private boolean isCallerEstablishedOwnerLocked() {
585 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700586 }
587
Paul Jensen0784eea2014-08-19 16:00:24 -0400588 // Note: Return type guarantees results are deduped and sorted, which callers require.
589 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
590 SortedSet<Integer> uids = new TreeSet<Integer>();
591 for (String app : packageNames) {
592 int uid = getAppUid(app, userHandle);
593 if (uid != -1) uids.add(uid);
594 }
595 return uids;
596 }
597
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400598 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400599 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800600 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700601 throw new IllegalStateException("VPN is not active");
602 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700603
Paul Jensen0784eea2014-08-19 16:00:24 -0400604 if (mConfig.allowedApplications != null) {
605 // Add ranges covering all UIDs for allowedApplications.
606 int start = -1, stop = -1;
607 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
608 if (start == -1) {
609 start = uid;
610 } else if (uid != stop + 1) {
611 mVpnUsers.add(new UidRange(start, stop));
612 start = uid;
613 }
614 stop = uid;
615 }
616 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
617 } else if (mConfig.disallowedApplications != null) {
618 // Add all ranges for user skipping UIDs for disallowedApplications.
619 final UidRange userRange = UidRange.createForUser(userHandle);
620 int start = userRange.start;
621 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
622 if (uid == start) {
623 start++;
624 } else {
625 mVpnUsers.add(new UidRange(start, uid - 1));
626 start = uid + 1;
627 }
628 }
629 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
630 } else {
631 // Add all UIDs for the user.
632 mVpnUsers.add(UidRange.createForUser(userHandle));
633 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700634
635 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700636 }
637
Paul Jensen0784eea2014-08-19 16:00:24 -0400638 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
639 // apply to userHandle.
640 private List<UidRange> uidRangesForUser(int userHandle) {
641 final UidRange userRange = UidRange.createForUser(userHandle);
642 final List<UidRange> ranges = new ArrayList<UidRange>();
643 for (UidRange range : mVpnUsers) {
644 if (range.start >= userRange.start && range.stop <= userRange.stop) {
645 ranges.add(range);
646 }
647 }
648 return ranges;
649 }
650
651 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800652 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700653 throw new IllegalStateException("VPN is not active");
654 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400655 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700656 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400657 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700658 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400659 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700660 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700661 }
662
Paul Jensen0784eea2014-08-19 16:00:24 -0400663 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700664 // If the user is restricted tie them to the owner's VPN
665 synchronized(Vpn.this) {
666 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400667 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700668 if (user.isRestricted()) {
669 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400670 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400671 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400672 final List<UidRange> ranges = uidRangesForUser(userHandle);
673 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400674 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700675 } catch (Exception e) {
676 Log.wtf(TAG, "Failed to add restricted user to owner", e);
677 }
678 }
679 }
680 }
681
Paul Jensen0784eea2014-08-19 16:00:24 -0400682 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700683 // clean up if restricted
684 synchronized(Vpn.this) {
685 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400686 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700687 if (user.isRestricted()) {
688 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400689 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700690 } catch (Exception e) {
691 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
692 }
693 }
694 }
695 }
696
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700697 /**
698 * Return the configuration of the currently running VPN.
699 */
700 public VpnConfig getVpnConfig() {
701 enforceControlPermission();
702 return mConfig;
703 }
704
Jeff Sharkey899223b2012-08-04 15:24:58 -0700705 @Deprecated
706 public synchronized void interfaceStatusChanged(String iface, boolean up) {
707 try {
708 mObserver.interfaceStatusChanged(iface, up);
709 } catch (RemoteException e) {
710 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700711 }
712 }
713
Jeff Sharkey899223b2012-08-04 15:24:58 -0700714 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
715 @Override
716 public void interfaceStatusChanged(String interfaze, boolean up) {
717 synchronized (Vpn.this) {
718 if (!up && mLegacyVpnRunner != null) {
719 mLegacyVpnRunner.check(interfaze);
720 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700721 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700722 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700723
Jeff Sharkey899223b2012-08-04 15:24:58 -0700724 @Override
725 public void interfaceRemoved(String interfaze) {
726 synchronized (Vpn.this) {
727 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700728 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400729 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500730 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700731 mInterface = null;
732 if (mConnection != null) {
733 mContext.unbindService(mConnection);
734 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400735 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700736 } else if (mLegacyVpnRunner != null) {
737 mLegacyVpnRunner.exit();
738 mLegacyVpnRunner = null;
739 }
740 }
741 }
742 }
743 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700744
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700745 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800746 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700747 }
748
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700749 private class Connection implements ServiceConnection {
750 private IBinder mService;
751
752 @Override
753 public void onServiceConnected(ComponentName name, IBinder service) {
754 mService = service;
755 }
756
757 @Override
758 public void onServiceDisconnected(ComponentName name) {
759 mService = null;
760 }
761 }
762
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700763 private void prepareStatusIntent() {
764 final long token = Binder.clearCallingIdentity();
765 try {
766 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
767 } finally {
768 Binder.restoreCallingIdentity(token);
769 }
770 }
771
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700772 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800773 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700774 return false;
775 }
776 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800777 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700778 return success;
779 }
780
781 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800782 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700783 return false;
784 }
785 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800786 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700787 return success;
788 }
789
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800790 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
791 if (!isCallerEstablishedOwnerLocked()) {
792 return false;
793 }
794 if (networks == null) {
795 mConfig.underlyingNetworks = null;
796 } else {
797 mConfig.underlyingNetworks = new Network[networks.length];
798 for (int i = 0; i < networks.length; ++i) {
799 if (networks[i] == null) {
800 mConfig.underlyingNetworks[i] = null;
801 } else {
802 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
803 }
804 }
805 }
806 return true;
807 }
808
809 public synchronized Network[] getUnderlyingNetworks() {
810 if (!isRunningLocked()) {
811 return null;
812 }
813 return mConfig.underlyingNetworks;
814 }
815
816 public synchronized boolean appliesToUid(int uid) {
817 if (!isRunningLocked()) {
818 return false;
819 }
820 for (UidRange uidRange : mVpnUsers) {
821 if (uidRange.start <= uid && uid <= uidRange.stop) {
822 return true;
823 }
824 }
825 return false;
826 }
827
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700828 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700829 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700830 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700831 private native void jniReset(String interfaze);
832 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700833 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
834 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700835
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900836 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
837 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700838 // Currently legacy VPN only works on IPv4.
839 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900840 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700841 }
842 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700843
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900844 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700845 }
846
847 /**
848 * Start legacy VPN, controlling native daemons as needed. Creates a
849 * secondary thread to perform connection work, returning quickly.
850 */
851 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800852 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800853 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700854 throw new IllegalStateException("KeyStore isn't unlocked");
855 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400856 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400857 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400858 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
859 throw new SecurityException("Restricted users cannot establish VPNs");
860 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700861
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900862 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
863 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
864 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700865
866 // Load certificates.
867 String privateKey = "";
868 String userCert = "";
869 String caCert = "";
870 String serverCert = "";
871 if (!profile.ipsecUserCert.isEmpty()) {
872 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
873 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700874 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700875 }
876 if (!profile.ipsecCaCert.isEmpty()) {
877 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700878 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700879 }
880 if (!profile.ipsecServerCert.isEmpty()) {
881 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700882 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700883 }
884 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
885 throw new IllegalStateException("Cannot load credentials");
886 }
887
888 // Prepare arguments for racoon.
889 String[] racoon = null;
890 switch (profile.type) {
891 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
892 racoon = new String[] {
893 iface, profile.server, "udppsk", profile.ipsecIdentifier,
894 profile.ipsecSecret, "1701",
895 };
896 break;
897 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
898 racoon = new String[] {
899 iface, profile.server, "udprsa", privateKey, userCert,
900 caCert, serverCert, "1701",
901 };
902 break;
903 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
904 racoon = new String[] {
905 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
906 profile.ipsecSecret, profile.username, profile.password, "", gateway,
907 };
908 break;
909 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
910 racoon = new String[] {
911 iface, profile.server, "xauthrsa", privateKey, userCert,
912 caCert, serverCert, profile.username, profile.password, "", gateway,
913 };
914 break;
915 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
916 racoon = new String[] {
917 iface, profile.server, "hybridrsa",
918 caCert, serverCert, profile.username, profile.password, "", gateway,
919 };
920 break;
921 }
922
923 // Prepare arguments for mtpd.
924 String[] mtpd = null;
925 switch (profile.type) {
926 case VpnProfile.TYPE_PPTP:
927 mtpd = new String[] {
928 iface, "pptp", profile.server, "1723",
929 "name", profile.username, "password", profile.password,
930 "linkname", "vpn", "refuse-eap", "nodefaultroute",
931 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
932 (profile.mppe ? "+mppe" : "nomppe"),
933 };
934 break;
935 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
936 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
937 mtpd = new String[] {
938 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
939 "name", profile.username, "password", profile.password,
940 "linkname", "vpn", "refuse-eap", "nodefaultroute",
941 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
942 };
943 break;
944 }
945
946 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700947 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700948 config.user = profile.key;
949 config.interfaze = iface;
950 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700951
952 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700953 if (!profile.dnsServers.isEmpty()) {
954 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
955 }
956 if (!profile.searchDomains.isEmpty()) {
957 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
958 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700959 startLegacyVpn(config, racoon, mtpd);
960 }
961
962 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
963 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700964
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700965 // Prepare for the new request. This also checks the caller.
966 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700967 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700968
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700969 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700970 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
971 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700972 }
973
Jeff Sharkey899223b2012-08-04 15:24:58 -0700974 public synchronized void stopLegacyVpn() {
975 if (mLegacyVpnRunner != null) {
976 mLegacyVpnRunner.exit();
977 mLegacyVpnRunner = null;
978
979 synchronized (LegacyVpnRunner.TAG) {
980 // wait for old thread to completely finish before spinning up
981 // new instance, otherwise state updates can be out of order.
982 }
983 }
984 }
985
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700986 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700987 * Return the information of the current ongoing legacy VPN.
988 */
989 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700990 // Check if the caller is authorized.
991 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700992 if (mLegacyVpnRunner == null) return null;
993
994 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700995 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700996 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700997 if (mNetworkInfo.isConnected()) {
998 info.intent = mStatusIntent;
999 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001000 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001001 }
1002
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001003 public VpnConfig getLegacyVpnConfig() {
1004 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001005 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001006 } else {
1007 return null;
1008 }
1009 }
1010
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001011 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001012 * Bringing up a VPN connection takes time, and that is all this thread
1013 * does. Here we have plenty of time. The only thing we need to take
1014 * care of is responding to interruptions as soon as possible. Otherwise
1015 * requests will be piled up. This can be done in a Handler as a state
1016 * machine, but it is much easier to read in the current form.
1017 */
1018 private class LegacyVpnRunner extends Thread {
1019 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001020
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001021 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001022 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001023 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001024 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001025 private final AtomicInteger mOuterConnection =
1026 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001027
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001028 private long mTimer = -1;
1029
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001030 /**
1031 * Watch for the outer connection (passing in the constructor) going away.
1032 */
1033 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1034 @Override
1035 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001036 if (!mEnableTeardown) return;
1037
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001038 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1039 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1040 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1041 NetworkInfo info = (NetworkInfo)intent.getExtra(
1042 ConnectivityManager.EXTRA_NETWORK_INFO);
1043 if (info != null && !info.isConnectedOrConnecting()) {
1044 try {
1045 mObserver.interfaceStatusChanged(mOuterInterface, false);
1046 } catch (RemoteException e) {}
1047 }
1048 }
1049 }
1050 }
1051 };
1052
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001053 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001055 mConfig = config;
1056 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001057 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001058 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001059 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001060
1061 // This is the interface which VPN is running on,
1062 // mConfig.interfaze will change to point to OUR
1063 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001064 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001065 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001066 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001067 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001068
1069 try {
1070 mOuterConnection.set(
1071 mConnService.findConnectionTypeForIface(mOuterInterface));
1072 } catch (Exception e) {
1073 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1074 }
1075
1076 IntentFilter filter = new IntentFilter();
1077 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1078 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001079 }
1080
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001081 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001082 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001083 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1084 exit();
1085 }
1086 }
1087
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001088 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001089 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001090 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001091 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001092 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001093 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001094 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001095 try {
1096 mContext.unregisterReceiver(mBroadcastReceiver);
1097 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001098 }
1099
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001100 @Override
1101 public void run() {
1102 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001103 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001104 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001105 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001106 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001107 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001108 }
1109 }
1110
1111 private void checkpoint(boolean yield) throws InterruptedException {
1112 long now = SystemClock.elapsedRealtime();
1113 if (mTimer == -1) {
1114 mTimer = now;
1115 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001116 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001117 Thread.sleep(yield ? 200 : 1);
1118 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001119 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001120 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001121 }
1122 }
1123
1124 private void execute() {
1125 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001126 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001127 try {
1128 // Initialize the timer.
1129 checkpoint(false);
1130
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001131 // Wait for the daemons to stop.
1132 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001133 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 checkpoint(true);
1135 }
1136 }
1137
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001138 // Clear the previous state.
1139 File state = new File("/data/misc/vpn/state");
1140 state.delete();
1141 if (state.exists()) {
1142 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001143 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001144 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001145 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146
Chia-chi Yehe9107902011-07-02 01:48:50 -07001147 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001148 boolean restart = false;
1149 for (String[] arguments : mArguments) {
1150 restart = restart || (arguments != null);
1151 }
1152 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001153 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001154 return;
1155 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001156 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001157
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001158 // Start the daemon with arguments.
1159 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160 String[] arguments = mArguments[i];
1161 if (arguments == null) {
1162 continue;
1163 }
1164
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001165 // Start the daemon.
1166 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001167 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001168
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001169 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001170 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171 checkpoint(true);
1172 }
1173
1174 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001175 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001176 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001177 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001178
1179 // Wait for the socket to connect.
1180 while (true) {
1181 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001182 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 break;
1184 } catch (Exception e) {
1185 // ignore
1186 }
1187 checkpoint(true);
1188 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001189 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001190
1191 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001192 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001193 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001194 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001195 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001196 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001197 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001198 out.write(bytes.length >> 8);
1199 out.write(bytes.length);
1200 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001201 checkpoint(false);
1202 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001203 out.write(0xFF);
1204 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001205 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001206
1207 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001208 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001209 while (true) {
1210 try {
1211 if (in.read() == -1) {
1212 break;
1213 }
1214 } catch (Exception e) {
1215 // ignore
1216 }
1217 checkpoint(true);
1218 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001219 }
1220
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001221 // Wait for the daemons to create the new state.
1222 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001223 // Check if a running daemon is dead.
1224 for (int i = 0; i < mDaemons.length; ++i) {
1225 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001226 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001227 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001228 }
1229 }
1230 checkpoint(true);
1231 }
1232
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001233 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001234 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001235 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001236 throw new IllegalStateException("Cannot parse the state");
1237 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001238
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001239 // Set the interface and the addresses in the config.
1240 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001241
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001242 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001243 // Set the routes if they are not set in the config.
1244 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001245 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001246 }
1247
1248 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001249 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001250 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001251 if (!dnsServers.isEmpty()) {
1252 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1253 }
1254 }
1255
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001256 // Set the search domains if they are not set in the config.
1257 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1258 String searchDomains = parameters[4].trim();
1259 if (!searchDomains.isEmpty()) {
1260 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1261 }
1262 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001263
Lorenzo Colitti50262792014-09-19 01:53:35 +09001264 // Add a throw route for the VPN server endpoint, if one was specified.
1265 String endpoint = parameters[5];
1266 if (!endpoint.isEmpty()) {
1267 try {
1268 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1269 if (addr instanceof Inet4Address) {
1270 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1271 } else if (addr instanceof Inet6Address) {
1272 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1273 } else {
1274 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1275 }
1276 } catch (IllegalArgumentException e) {
1277 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1278 }
1279 }
1280
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001281 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001282 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001283 // Set the start time
1284 mConfig.startTime = SystemClock.elapsedRealtime();
1285
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001286 // Check if the thread is interrupted while we are waiting.
1287 checkpoint(false);
1288
Chia-chi Yehe9107902011-07-02 01:48:50 -07001289 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001290 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001291 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001292 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001293
1294 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001295 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001296 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001297
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001298 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001299
1300 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001301 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001302 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001303 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001304 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001305 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001306 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001307 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001308 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001309 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001310 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001311 }
1312 }
1313
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001314 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001315 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001316 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001317 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001318 }
1319 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001320
1321 /**
1322 * Monitor the daemons we started, moving to disconnected state if the
1323 * underlying services fail.
1324 */
1325 private void monitorDaemons() {
1326 if (!mNetworkInfo.isConnected()) {
1327 return;
1328 }
1329
1330 try {
1331 while (true) {
1332 Thread.sleep(2000);
1333 for (int i = 0; i < mDaemons.length; i++) {
1334 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1335 return;
1336 }
1337 }
1338 }
1339 } catch (InterruptedException e) {
1340 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1341 } finally {
1342 for (String daemon : mDaemons) {
1343 SystemService.stop(daemon);
1344 }
1345
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001346 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001347 }
1348 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001349 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001350}