blob: d9c96f21889376c3b66364df83e58a06b8d8f47b [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;
Jeff Sharkey82f85212012-08-24 11:17:25 -070079import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070080import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070081
Jeff Davidson05542602014-08-11 14:07:27 -070082import libcore.io.IoUtils;
83
Chia-chi Yeh97a61562011-07-14 15:05:05 -070084import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070085import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070086import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070087import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070089import java.net.Inet6Address;
90import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070091import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040092import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070093import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040094import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040095import java.util.SortedSet;
96import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070097import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070098
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070099/**
100 * @hide
101 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400102public class Vpn {
103 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700104 private static final String TAG = "Vpn";
105 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106
Jeff Sharkey899223b2012-08-04 15:24:58 -0700107 // TODO: create separate trackers for each unique VPN to support
108 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700109
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400110 private Context mContext;
111 private NetworkInfo mNetworkInfo;
112 private String mPackage;
113 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700114 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700115 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700116 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700117 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700118 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400119 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700120 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400121 private NetworkAgent mNetworkAgent;
122 private final Looper mLooper;
123 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700124
125 /* list of users using this VPN. */
126 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400127 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700128 private BroadcastReceiver mUserIntentReceiver = null;
129
Paul Jensen0784eea2014-08-19 16:00:24 -0400130 // Handle of user initiating VPN.
131 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700132
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400133 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400134 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700135 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400136 mNetd = netService;
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
Paul Jensen31a94f42015-02-13 14:18:39 -0500343 public int getNetId() {
344 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
345 }
346
Lorenzo Colitti60446162014-09-20 00:14:31 +0900347 private LinkProperties makeLinkProperties() {
348 boolean allowIPv4 = mConfig.allowIPv4;
349 boolean allowIPv6 = mConfig.allowIPv6;
350
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400351 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900352
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400353 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700354
Lorenzo Colitti60446162014-09-20 00:14:31 +0900355 if (mConfig.addresses != null) {
356 for (LinkAddress address : mConfig.addresses) {
357 lp.addLinkAddress(address);
358 allowIPv4 |= address.getAddress() instanceof Inet4Address;
359 allowIPv6 |= address.getAddress() instanceof Inet6Address;
360 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400361 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900362
363 if (mConfig.routes != null) {
364 for (RouteInfo route : mConfig.routes) {
365 lp.addRoute(route);
366 InetAddress address = route.getDestination().getAddress();
367 allowIPv4 |= address instanceof Inet4Address;
368 allowIPv6 |= address instanceof Inet6Address;
369 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400370 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700371
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400372 if (mConfig.dnsServers != null) {
373 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700374 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
375 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900376 allowIPv4 |= address instanceof Inet4Address;
377 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400378 }
379 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700380
Lorenzo Colitti60446162014-09-20 00:14:31 +0900381 if (!allowIPv4) {
382 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
383 }
384 if (!allowIPv6) {
385 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
386 }
387
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 // Concatenate search domains into a string.
389 StringBuilder buffer = new StringBuilder();
390 if (mConfig.searchDomains != null) {
391 for (String domain : mConfig.searchDomains) {
392 buffer.append(domain).append(' ');
393 }
394 }
395 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700396
Lorenzo Colitti60446162014-09-20 00:14:31 +0900397 // TODO: Stop setting the MTU in jniCreate and set it here.
398
399 return lp;
400 }
401
402 private void agentConnect() {
403 LinkProperties lp = makeLinkProperties();
404
405 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
406 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
407 } else {
408 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
409 }
410
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400411 mNetworkInfo.setIsAvailable(true);
412 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700413
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700414 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700415 networkMisc.allowBypass = mConfig.allowBypass;
416
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400417 long token = Binder.clearCallingIdentity();
418 try {
419 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700420 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700421 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400422 public void unwanted() {
423 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700424 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400425 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700426 } finally {
427 Binder.restoreCallingIdentity(token);
428 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700429
Paul Jensen0784eea2014-08-19 16:00:24 -0400430 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400431 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400432 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400433 token = Binder.clearCallingIdentity();
434 List<UserInfo> users;
435 try {
436 users = UserManager.get(mContext).getUsers();
437 } finally {
438 Binder.restoreCallingIdentity(token);
439 }
440 for (UserInfo user : users) {
441 if (user.isRestricted()) {
442 addVpnUserLocked(user.id);
443 }
444 }
445 }
446 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
447 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700448
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400449 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
450 networkInfo.setIsAvailable(false);
451 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
452 if (networkAgent != null) {
453 networkAgent.sendNetworkInfo(networkInfo);
454 }
455 }
456
457 private void agentDisconnect(NetworkAgent networkAgent) {
458 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
459 agentDisconnect(networkInfo, networkAgent);
460 }
461
462 private void agentDisconnect() {
463 if (mNetworkInfo.isConnected()) {
464 agentDisconnect(mNetworkInfo, mNetworkAgent);
465 mNetworkAgent = null;
466 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700467 }
468
469 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700470 * Establish a VPN network and return the file descriptor of the VPN
471 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700472 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700473 *
474 * @param config The parameters to configure the network.
475 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700476 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700477 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700478 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700479 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400480 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700481 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700482 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700483 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700484 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
485 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700486 long token = Binder.clearCallingIdentity();
487 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700488 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400489 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400490 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700491 throw new SecurityException("Restricted users cannot establish VPNs");
492 }
493
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700494 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400495 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700496 if (info == null) {
497 throw new SecurityException("Cannot find " + config.user);
498 }
499 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
500 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
501 }
502 } catch (RemoteException e) {
503 throw new SecurityException("Cannot find " + config.user);
504 } finally {
505 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700506 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700507
Chad Brubaker850eb672014-03-21 21:02:47 +0000508 // Save the old config in case we need to go back.
509 VpnConfig oldConfig = mConfig;
510 String oldInterface = mInterface;
511 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400512 NetworkAgent oldNetworkAgent = mNetworkAgent;
513 mNetworkAgent = null;
514 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000515
Chia-chi Yehe9107902011-07-02 01:48:50 -0700516 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700517 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700518 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700519 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700520 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700521
Chad Brubakerc2865192013-07-10 14:46:23 -0700522 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700523 StringBuilder builder = new StringBuilder();
524 for (LinkAddress address : config.addresses) {
525 builder.append(" " + address);
526 }
527 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700528 throw new IllegalArgumentException("At least one address must be specified");
529 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700530 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700531 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400532 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700533 throw new IllegalStateException("Cannot bind " + config.user);
534 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000535
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700536 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700537 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700538
539 // Fill more values.
540 config.user = mPackage;
541 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700542 config.startTime = SystemClock.elapsedRealtime();
543 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000544
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700545 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400546 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700547
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000549
550 if (oldConnection != null) {
551 mContext.unbindService(oldConnection);
552 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400553 // Remove the old tun's user forwarding rules
554 // The new tun's user rules have already been added so they will take over
555 // as rules are deleted. This prevents data leakage as the rules are moved over.
556 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000557 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000558 jniReset(oldInterface);
559 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700560
561 try {
562 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
563 } catch (IOException e) {
564 throw new IllegalStateException(
565 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
566 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000567 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000568 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 // restore old state
571 mConfig = oldConfig;
572 mConnection = oldConnection;
573 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400574 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000575 mInterface = oldInterface;
576 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000578 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700579 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700580 }
581
Chad Brubakerc2865192013-07-10 14:46:23 -0700582 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800583 return mNetworkAgent != null && mInterface != null;
584 }
585
586 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
587 // that a call to mutate VPN state is admissible.
588 private boolean isCallerEstablishedOwnerLocked() {
589 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700590 }
591
Paul Jensen0784eea2014-08-19 16:00:24 -0400592 // Note: Return type guarantees results are deduped and sorted, which callers require.
593 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
594 SortedSet<Integer> uids = new TreeSet<Integer>();
595 for (String app : packageNames) {
596 int uid = getAppUid(app, userHandle);
597 if (uid != -1) uids.add(uid);
598 }
599 return uids;
600 }
601
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400602 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400603 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800604 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700605 throw new IllegalStateException("VPN is not active");
606 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700607
Paul Jensen0784eea2014-08-19 16:00:24 -0400608 if (mConfig.allowedApplications != null) {
609 // Add ranges covering all UIDs for allowedApplications.
610 int start = -1, stop = -1;
611 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
612 if (start == -1) {
613 start = uid;
614 } else if (uid != stop + 1) {
615 mVpnUsers.add(new UidRange(start, stop));
616 start = uid;
617 }
618 stop = uid;
619 }
620 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
621 } else if (mConfig.disallowedApplications != null) {
622 // Add all ranges for user skipping UIDs for disallowedApplications.
623 final UidRange userRange = UidRange.createForUser(userHandle);
624 int start = userRange.start;
625 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
626 if (uid == start) {
627 start++;
628 } else {
629 mVpnUsers.add(new UidRange(start, uid - 1));
630 start = uid + 1;
631 }
632 }
633 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
634 } else {
635 // Add all UIDs for the user.
636 mVpnUsers.add(UidRange.createForUser(userHandle));
637 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700638
639 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700640 }
641
Paul Jensen0784eea2014-08-19 16:00:24 -0400642 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
643 // apply to userHandle.
644 private List<UidRange> uidRangesForUser(int userHandle) {
645 final UidRange userRange = UidRange.createForUser(userHandle);
646 final List<UidRange> ranges = new ArrayList<UidRange>();
647 for (UidRange range : mVpnUsers) {
648 if (range.start >= userRange.start && range.stop <= userRange.stop) {
649 ranges.add(range);
650 }
651 }
652 return ranges;
653 }
654
655 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800656 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700657 throw new IllegalStateException("VPN is not active");
658 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400659 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700660 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400661 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700662 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400663 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700664 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700665 }
666
Paul Jensen0784eea2014-08-19 16:00:24 -0400667 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700668 // If the user is restricted tie them to the owner's VPN
669 synchronized(Vpn.this) {
670 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400671 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700672 if (user.isRestricted()) {
673 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400674 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400675 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400676 final List<UidRange> ranges = uidRangesForUser(userHandle);
677 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400678 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700679 } catch (Exception e) {
680 Log.wtf(TAG, "Failed to add restricted user to owner", e);
681 }
682 }
683 }
684 }
685
Paul Jensen0784eea2014-08-19 16:00:24 -0400686 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700687 // clean up if restricted
688 synchronized(Vpn.this) {
689 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400690 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700691 if (user.isRestricted()) {
692 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400693 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700694 } catch (Exception e) {
695 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
696 }
697 }
698 }
699 }
700
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700701 /**
702 * Return the configuration of the currently running VPN.
703 */
704 public VpnConfig getVpnConfig() {
705 enforceControlPermission();
706 return mConfig;
707 }
708
Jeff Sharkey899223b2012-08-04 15:24:58 -0700709 @Deprecated
710 public synchronized void interfaceStatusChanged(String iface, boolean up) {
711 try {
712 mObserver.interfaceStatusChanged(iface, up);
713 } catch (RemoteException e) {
714 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700715 }
716 }
717
Jeff Sharkey899223b2012-08-04 15:24:58 -0700718 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
719 @Override
720 public void interfaceStatusChanged(String interfaze, boolean up) {
721 synchronized (Vpn.this) {
722 if (!up && mLegacyVpnRunner != null) {
723 mLegacyVpnRunner.check(interfaze);
724 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700725 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700726 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700727
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 @Override
729 public void interfaceRemoved(String interfaze) {
730 synchronized (Vpn.this) {
731 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700732 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400733 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700734 mInterface = null;
735 if (mConnection != null) {
736 mContext.unbindService(mConnection);
737 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400738 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700739 } else if (mLegacyVpnRunner != null) {
740 mLegacyVpnRunner.exit();
741 mLegacyVpnRunner = null;
742 }
743 }
744 }
745 }
746 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700747
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700748 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800749 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700750 }
751
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700752 private class Connection implements ServiceConnection {
753 private IBinder mService;
754
755 @Override
756 public void onServiceConnected(ComponentName name, IBinder service) {
757 mService = service;
758 }
759
760 @Override
761 public void onServiceDisconnected(ComponentName name) {
762 mService = null;
763 }
764 }
765
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700766 private void prepareStatusIntent() {
767 final long token = Binder.clearCallingIdentity();
768 try {
769 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
770 } finally {
771 Binder.restoreCallingIdentity(token);
772 }
773 }
774
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700775 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800776 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700777 return false;
778 }
779 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800780 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700781 return success;
782 }
783
784 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800785 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700786 return false;
787 }
788 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800789 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700790 return success;
791 }
792
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800793 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
794 if (!isCallerEstablishedOwnerLocked()) {
795 return false;
796 }
797 if (networks == null) {
798 mConfig.underlyingNetworks = null;
799 } else {
800 mConfig.underlyingNetworks = new Network[networks.length];
801 for (int i = 0; i < networks.length; ++i) {
802 if (networks[i] == null) {
803 mConfig.underlyingNetworks[i] = null;
804 } else {
805 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
806 }
807 }
808 }
809 return true;
810 }
811
812 public synchronized Network[] getUnderlyingNetworks() {
813 if (!isRunningLocked()) {
814 return null;
815 }
816 return mConfig.underlyingNetworks;
817 }
818
819 public synchronized boolean appliesToUid(int uid) {
820 if (!isRunningLocked()) {
821 return false;
822 }
823 for (UidRange uidRange : mVpnUsers) {
824 if (uidRange.start <= uid && uid <= uidRange.stop) {
825 return true;
826 }
827 }
828 return false;
829 }
830
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700831 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700832 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700833 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700834 private native void jniReset(String interfaze);
835 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700836 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
837 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700838
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900839 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
840 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700841 // Currently legacy VPN only works on IPv4.
842 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900843 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700844 }
845 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700846
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900847 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700848 }
849
850 /**
851 * Start legacy VPN, controlling native daemons as needed. Creates a
852 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800853 *
854 * Should only be called to respond to Binder requests as this enforces caller permission. Use
855 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
856 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700857 */
858 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800859 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800860 long token = Binder.clearCallingIdentity();
861 try {
862 startLegacyVpnPrivileged(profile, keyStore, egress);
863 } finally {
864 Binder.restoreCallingIdentity(token);
865 }
866 }
867
868 /**
869 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
870 * permissions under the assumption that the caller is the system.
871 *
872 * Callers are responsible for checking permissions if needed.
873 */
874 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
875 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800876 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700877 throw new IllegalStateException("KeyStore isn't unlocked");
878 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400879 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400880 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400881 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
882 throw new SecurityException("Restricted users cannot establish VPNs");
883 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700884
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900885 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
886 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
887 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700888
889 // Load certificates.
890 String privateKey = "";
891 String userCert = "";
892 String caCert = "";
893 String serverCert = "";
894 if (!profile.ipsecUserCert.isEmpty()) {
895 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
896 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700897 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700898 }
899 if (!profile.ipsecCaCert.isEmpty()) {
900 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700901 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700902 }
903 if (!profile.ipsecServerCert.isEmpty()) {
904 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700905 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700906 }
907 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
908 throw new IllegalStateException("Cannot load credentials");
909 }
910
911 // Prepare arguments for racoon.
912 String[] racoon = null;
913 switch (profile.type) {
914 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
915 racoon = new String[] {
916 iface, profile.server, "udppsk", profile.ipsecIdentifier,
917 profile.ipsecSecret, "1701",
918 };
919 break;
920 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
921 racoon = new String[] {
922 iface, profile.server, "udprsa", privateKey, userCert,
923 caCert, serverCert, "1701",
924 };
925 break;
926 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
927 racoon = new String[] {
928 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
929 profile.ipsecSecret, profile.username, profile.password, "", gateway,
930 };
931 break;
932 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
933 racoon = new String[] {
934 iface, profile.server, "xauthrsa", privateKey, userCert,
935 caCert, serverCert, profile.username, profile.password, "", gateway,
936 };
937 break;
938 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
939 racoon = new String[] {
940 iface, profile.server, "hybridrsa",
941 caCert, serverCert, profile.username, profile.password, "", gateway,
942 };
943 break;
944 }
945
946 // Prepare arguments for mtpd.
947 String[] mtpd = null;
948 switch (profile.type) {
949 case VpnProfile.TYPE_PPTP:
950 mtpd = new String[] {
951 iface, "pptp", profile.server, "1723",
952 "name", profile.username, "password", profile.password,
953 "linkname", "vpn", "refuse-eap", "nodefaultroute",
954 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
955 (profile.mppe ? "+mppe" : "nomppe"),
956 };
957 break;
958 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
959 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
960 mtpd = new String[] {
961 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
962 "name", profile.username, "password", profile.password,
963 "linkname", "vpn", "refuse-eap", "nodefaultroute",
964 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
965 };
966 break;
967 }
968
969 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700970 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700971 config.user = profile.key;
972 config.interfaze = iface;
973 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700974
975 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700976 if (!profile.dnsServers.isEmpty()) {
977 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
978 }
979 if (!profile.searchDomains.isEmpty()) {
980 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
981 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700982 startLegacyVpn(config, racoon, mtpd);
983 }
984
985 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800986 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700987
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800988 // Prepare for the new request.
989 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700990 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700991
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700992 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700993 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
994 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700995 }
996
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800997 /** Stop legacy VPN. Permissions must be checked by callers. */
998 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700999 if (mLegacyVpnRunner != null) {
1000 mLegacyVpnRunner.exit();
1001 mLegacyVpnRunner = null;
1002
1003 synchronized (LegacyVpnRunner.TAG) {
1004 // wait for old thread to completely finish before spinning up
1005 // new instance, otherwise state updates can be out of order.
1006 }
1007 }
1008 }
1009
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001010 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001011 * Return the information of the current ongoing legacy VPN.
1012 */
1013 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001014 // Check if the caller is authorized.
1015 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001016 if (mLegacyVpnRunner == null) return null;
1017
1018 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001019 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001020 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001021 if (mNetworkInfo.isConnected()) {
1022 info.intent = mStatusIntent;
1023 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001024 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001025 }
1026
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001027 public VpnConfig getLegacyVpnConfig() {
1028 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001029 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001030 } else {
1031 return null;
1032 }
1033 }
1034
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001035 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001036 * Bringing up a VPN connection takes time, and that is all this thread
1037 * does. Here we have plenty of time. The only thing we need to take
1038 * care of is responding to interruptions as soon as possible. Otherwise
1039 * requests will be piled up. This can be done in a Handler as a state
1040 * machine, but it is much easier to read in the current form.
1041 */
1042 private class LegacyVpnRunner extends Thread {
1043 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001045 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001046 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001047 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001048 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001049 private final AtomicInteger mOuterConnection =
1050 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001051
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001052 private long mTimer = -1;
1053
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001054 /**
1055 * Watch for the outer connection (passing in the constructor) going away.
1056 */
1057 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1058 @Override
1059 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001060 if (!mEnableTeardown) return;
1061
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001062 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1063 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1064 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1065 NetworkInfo info = (NetworkInfo)intent.getExtra(
1066 ConnectivityManager.EXTRA_NETWORK_INFO);
1067 if (info != null && !info.isConnectedOrConnecting()) {
1068 try {
1069 mObserver.interfaceStatusChanged(mOuterInterface, false);
1070 } catch (RemoteException e) {}
1071 }
1072 }
1073 }
1074 }
1075 };
1076
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001077 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001078 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001079 mConfig = config;
1080 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001081 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001082 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001083 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001084
1085 // This is the interface which VPN is running on,
1086 // mConfig.interfaze will change to point to OUR
1087 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001088 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001089 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001090 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001091 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001092
Paul Jensene75b9e32015-04-06 11:54:53 -04001093 if (!TextUtils.isEmpty(mOuterInterface)) {
1094 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1095 for (Network network : cm.getAllNetworks()) {
1096 final LinkProperties lp = cm.getLinkProperties(network);
1097 if (lp != null && mOuterInterface.equals(lp.getInterfaceName())) {
1098 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1099 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1100 }
1101 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001102 }
1103
1104 IntentFilter filter = new IntentFilter();
1105 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1106 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001107 }
1108
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001109 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001110 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001111 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1112 exit();
1113 }
1114 }
1115
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001116 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001117 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001118 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001119 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001120 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001121 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001122 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001123 try {
1124 mContext.unregisterReceiver(mBroadcastReceiver);
1125 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001126 }
1127
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001128 @Override
1129 public void run() {
1130 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001131 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001132 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001133 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001135 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001136 }
1137 }
1138
1139 private void checkpoint(boolean yield) throws InterruptedException {
1140 long now = SystemClock.elapsedRealtime();
1141 if (mTimer == -1) {
1142 mTimer = now;
1143 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001144 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001145 Thread.sleep(yield ? 200 : 1);
1146 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001147 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001148 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001149 }
1150 }
1151
1152 private void execute() {
1153 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001154 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001155 try {
1156 // Initialize the timer.
1157 checkpoint(false);
1158
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001159 // Wait for the daemons to stop.
1160 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001161 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001162 checkpoint(true);
1163 }
1164 }
1165
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001166 // Clear the previous state.
1167 File state = new File("/data/misc/vpn/state");
1168 state.delete();
1169 if (state.exists()) {
1170 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001172 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001173 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001174
Chia-chi Yehe9107902011-07-02 01:48:50 -07001175 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001176 boolean restart = false;
1177 for (String[] arguments : mArguments) {
1178 restart = restart || (arguments != null);
1179 }
1180 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001181 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001182 return;
1183 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001184 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001185
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001186 // Start the daemon with arguments.
1187 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001188 String[] arguments = mArguments[i];
1189 if (arguments == null) {
1190 continue;
1191 }
1192
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001193 // Start the daemon.
1194 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001195 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001196
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001197 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001198 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001199 checkpoint(true);
1200 }
1201
1202 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001203 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001204 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001205 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001206
1207 // Wait for the socket to connect.
1208 while (true) {
1209 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001210 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001211 break;
1212 } catch (Exception e) {
1213 // ignore
1214 }
1215 checkpoint(true);
1216 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001217 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001218
1219 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001220 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001221 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001222 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001223 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001224 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001225 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001226 out.write(bytes.length >> 8);
1227 out.write(bytes.length);
1228 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 checkpoint(false);
1230 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001231 out.write(0xFF);
1232 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001233 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001234
1235 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001236 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001237 while (true) {
1238 try {
1239 if (in.read() == -1) {
1240 break;
1241 }
1242 } catch (Exception e) {
1243 // ignore
1244 }
1245 checkpoint(true);
1246 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001247 }
1248
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001249 // Wait for the daemons to create the new state.
1250 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001251 // Check if a running daemon is dead.
1252 for (int i = 0; i < mDaemons.length; ++i) {
1253 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001254 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001255 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001256 }
1257 }
1258 checkpoint(true);
1259 }
1260
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001261 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001262 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001263 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001264 throw new IllegalStateException("Cannot parse the state");
1265 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001266
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001267 // Set the interface and the addresses in the config.
1268 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001269
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001270 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001271 // Set the routes if they are not set in the config.
1272 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001273 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001274 }
1275
1276 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001277 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001278 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001279 if (!dnsServers.isEmpty()) {
1280 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1281 }
1282 }
1283
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001284 // Set the search domains if they are not set in the config.
1285 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1286 String searchDomains = parameters[4].trim();
1287 if (!searchDomains.isEmpty()) {
1288 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1289 }
1290 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001291
Lorenzo Colitti50262792014-09-19 01:53:35 +09001292 // Add a throw route for the VPN server endpoint, if one was specified.
1293 String endpoint = parameters[5];
1294 if (!endpoint.isEmpty()) {
1295 try {
1296 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1297 if (addr instanceof Inet4Address) {
1298 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1299 } else if (addr instanceof Inet6Address) {
1300 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1301 } else {
1302 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1303 }
1304 } catch (IllegalArgumentException e) {
1305 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1306 }
1307 }
1308
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001309 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001310 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001311 // Set the start time
1312 mConfig.startTime = SystemClock.elapsedRealtime();
1313
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001314 // Check if the thread is interrupted while we are waiting.
1315 checkpoint(false);
1316
Chia-chi Yehe9107902011-07-02 01:48:50 -07001317 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001318 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001319 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001320 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001321
1322 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001323 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001324 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001325
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001326 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001327
1328 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001329 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001330 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001331 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001332 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001333 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001334 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001335 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001336 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001337 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001338 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001339 }
1340 }
1341
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001342 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001343 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001344 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001345 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001346 }
1347 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001348
1349 /**
1350 * Monitor the daemons we started, moving to disconnected state if the
1351 * underlying services fail.
1352 */
1353 private void monitorDaemons() {
1354 if (!mNetworkInfo.isConnected()) {
1355 return;
1356 }
1357
1358 try {
1359 while (true) {
1360 Thread.sleep(2000);
1361 for (int i = 0; i < mDaemons.length; i++) {
1362 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1363 return;
1364 }
1365 }
1366 }
1367 } catch (InterruptedException e) {
1368 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1369 } finally {
1370 for (String daemon : mDaemons) {
1371 SystemService.stop(daemon);
1372 }
1373
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001374 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001375 }
1376 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001377 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001378}