blob: 0896955117821c0a374defb8de58e34586843e39 [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;
Paul Jensene75b9e32015-04-06 11:54:53 -040072import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070073import android.util.Log;
74
Chad Brubakerc2865192013-07-10 14:46:23 -070075import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070076import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070077import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070078import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070079import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070080
Jeff Davidson05542602014-08-11 14:07:27 -070081import libcore.io.IoUtils;
82
Chia-chi Yeh97a61562011-07-14 15:05:05 -070083import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070084import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070085import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070086import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070088import java.net.Inet6Address;
89import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070090import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070092import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040093import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040094import java.util.SortedSet;
95import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070096import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070097
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098/**
99 * @hide
100 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400101public class Vpn {
102 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700103 private static final String TAG = "Vpn";
104 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400105
Jeff Sharkey899223b2012-08-04 15:24:58 -0700106 // TODO: create separate trackers for each unique VPN to support
107 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700108
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400109 private Context mContext;
110 private NetworkInfo mNetworkInfo;
111 private String mPackage;
112 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700113 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700114 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700115 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700116 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700117 private volatile boolean mEnableTeardown = true;
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 Jensene75b9e32015-04-06 11:54:53 -0400133 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700134 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400135 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400136 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mLooper = looper;
138
139 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400140 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700141
142 try {
143 netService.registerObserver(mObserver);
144 } catch (RemoteException e) {
145 Log.wtf(TAG, "Problem registering observer", e);
146 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400147 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700148 // Owner's VPN also needs to handle restricted users
149 mUserIntentReceiver = new BroadcastReceiver() {
150 @Override
151 public void onReceive(Context context, Intent intent) {
152 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400153 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700154 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700156
157 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400158 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700159 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400160 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700161 }
162 }
163 };
164
165 IntentFilter intentFilter = new IntentFilter();
166 intentFilter.addAction(Intent.ACTION_USER_ADDED);
167 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
168 mContext.registerReceiverAsUser(
169 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
170 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400171
172 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
173 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
174 mNetworkCapabilities = new NetworkCapabilities();
175 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
176 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700177 }
178
Jeff Sharkey57666932013-04-30 17:01:57 -0700179 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700180 * Set if this object is responsible for watching for {@link NetworkInfo}
181 * teardown. When {@code false}, teardown is handled externally by someone
182 * else.
183 */
184 public void setEnableTeardown(boolean enableTeardown) {
185 mEnableTeardown = enableTeardown;
186 }
187
Jeff Sharkey899223b2012-08-04 15:24:58 -0700188 /**
189 * Update current state, dispaching event to listeners.
190 */
191 private void updateState(DetailedState detailedState, String reason) {
192 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
193 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400194 if (mNetworkAgent != null) {
195 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
196 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197 }
198
199 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700200 * Prepare for a VPN application. This method is designed to solve
201 * race conditions. It first compares the current prepared package
202 * with {@code oldPackage}. If they are the same, the prepared
203 * package is revoked and replaced with {@code newPackage}. If
204 * {@code oldPackage} is {@code null}, the comparison is omitted.
205 * If {@code newPackage} is the same package or {@code null}, the
206 * revocation is omitted. This method returns {@code true} if the
207 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700208 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700209 * Legacy VPN is handled specially since it is not a real package.
210 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
211 * it can be revoked by itself.
212 *
213 * @param oldPackage The package name of the old VPN application.
214 * @param newPackage The package name of the new VPN application.
215 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700216 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700217 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidsonbe085872014-10-24 10:35:53 -0700218 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800219 // The package doesn't match. We return false (to obtain user consent) unless the user
220 // has already consented to that VPN package.
Jeff Davidson05542602014-08-11 14:07:27 -0700221 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800222 prepareInternal(oldPackage);
Jeff Davidson05542602014-08-11 14:07:27 -0700223 return true;
224 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700225 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700226 }
227
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700228 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700229 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
230 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700231 return true;
232 }
233
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700234 // Check if the caller is authorized.
235 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700236
Jeff Davidson11008a72014-11-20 13:12:46 -0800237 prepareInternal(newPackage);
238 return true;
239 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700240
Jeff Davidson11008a72014-11-20 13:12:46 -0800241 /** Prepare the VPN for the given package. Does not perform permission checks. */
242 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400243 long token = Binder.clearCallingIdentity();
244 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800245 // Reset the interface.
246 if (mInterface != null) {
247 mStatusIntent = null;
248 agentDisconnect();
249 jniReset(mInterface);
250 mInterface = null;
251 mVpnUsers = null;
252 }
253
254 // Revoke the connection or stop LegacyVpnRunner.
255 if (mConnection != null) {
256 try {
257 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
258 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
259 } catch (Exception e) {
260 // ignore
261 }
262 mContext.unbindService(mConnection);
263 mConnection = null;
264 } else if (mLegacyVpnRunner != null) {
265 mLegacyVpnRunner.exit();
266 mLegacyVpnRunner = null;
267 }
268
269 try {
270 mNetd.denyProtect(mOwnerUID);
271 } catch (Exception e) {
272 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
273 }
274
275 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
276 mPackage = newPackage;
277 mOwnerUID = getAppUid(newPackage, mUserHandle);
278 try {
279 mNetd.allowProtect(mOwnerUID);
280 } catch (Exception e) {
281 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
282 }
283 mConfig = null;
284
285 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400286 } finally {
287 Binder.restoreCallingIdentity(token);
288 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700289 }
290
Jeff Davidson05542602014-08-11 14:07:27 -0700291 /**
292 * Set whether the current package has the ability to launch VPNs without user intervention.
293 */
294 public void setPackageAuthorization(boolean authorized) {
295 // Check if the caller is authorized.
296 enforceControlPermission();
297
298 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
299 return;
300 }
301
302 long token = Binder.clearCallingIdentity();
303 try {
304 AppOpsManager appOps =
305 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
306 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
307 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
308 } catch (Exception e) {
309 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
310 } finally {
311 Binder.restoreCallingIdentity(token);
312 }
313 }
314
315 private boolean isVpnUserPreConsented(String packageName) {
316 AppOpsManager appOps =
317 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
318
319 // Verify that the caller matches the given package and has permission to activate VPNs.
320 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
321 packageName) == AppOpsManager.MODE_ALLOWED;
322 }
323
Paul Jensen0784eea2014-08-19 16:00:24 -0400324 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700325 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400326 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700327 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400328 PackageManager pm = mContext.getPackageManager();
329 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700330 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400331 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400332 } catch (NameNotFoundException e) {
333 result = -1;
334 }
335 return result;
336 }
337
338 public NetworkInfo getNetworkInfo() {
339 return mNetworkInfo;
340 }
341
Lorenzo Colitti60446162014-09-20 00:14:31 +0900342 private LinkProperties makeLinkProperties() {
343 boolean allowIPv4 = mConfig.allowIPv4;
344 boolean allowIPv6 = mConfig.allowIPv6;
345
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400346 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900347
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400348 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700349
Lorenzo Colitti60446162014-09-20 00:14:31 +0900350 if (mConfig.addresses != null) {
351 for (LinkAddress address : mConfig.addresses) {
352 lp.addLinkAddress(address);
353 allowIPv4 |= address.getAddress() instanceof Inet4Address;
354 allowIPv6 |= address.getAddress() instanceof Inet6Address;
355 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400356 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900357
358 if (mConfig.routes != null) {
359 for (RouteInfo route : mConfig.routes) {
360 lp.addRoute(route);
361 InetAddress address = route.getDestination().getAddress();
362 allowIPv4 |= address instanceof Inet4Address;
363 allowIPv6 |= address instanceof Inet6Address;
364 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400365 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700366
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400367 if (mConfig.dnsServers != null) {
368 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700369 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
370 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900371 allowIPv4 |= address instanceof Inet4Address;
372 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400373 }
374 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700375
Lorenzo Colitti60446162014-09-20 00:14:31 +0900376 if (!allowIPv4) {
377 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
378 }
379 if (!allowIPv6) {
380 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
381 }
382
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400383 // Concatenate search domains into a string.
384 StringBuilder buffer = new StringBuilder();
385 if (mConfig.searchDomains != null) {
386 for (String domain : mConfig.searchDomains) {
387 buffer.append(domain).append(' ');
388 }
389 }
390 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700391
Lorenzo Colitti60446162014-09-20 00:14:31 +0900392 // TODO: Stop setting the MTU in jniCreate and set it here.
393
394 return lp;
395 }
396
397 private void agentConnect() {
398 LinkProperties lp = makeLinkProperties();
399
400 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
401 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
402 } else {
403 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
404 }
405
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400406 mNetworkInfo.setIsAvailable(true);
407 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700408
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700409 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700410 networkMisc.allowBypass = mConfig.allowBypass;
411
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400412 long token = Binder.clearCallingIdentity();
413 try {
414 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700415 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700416 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400417 public void unwanted() {
418 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700419 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400420 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700421 } finally {
422 Binder.restoreCallingIdentity(token);
423 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700424
Paul Jensen0784eea2014-08-19 16:00:24 -0400425 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400426 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400427 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400428 token = Binder.clearCallingIdentity();
429 List<UserInfo> users;
430 try {
431 users = UserManager.get(mContext).getUsers();
432 } finally {
433 Binder.restoreCallingIdentity(token);
434 }
435 for (UserInfo user : users) {
436 if (user.isRestricted()) {
437 addVpnUserLocked(user.id);
438 }
439 }
440 }
441 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
442 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700443
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400444 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
445 networkInfo.setIsAvailable(false);
446 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
447 if (networkAgent != null) {
448 networkAgent.sendNetworkInfo(networkInfo);
449 }
450 }
451
452 private void agentDisconnect(NetworkAgent networkAgent) {
453 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
454 agentDisconnect(networkInfo, networkAgent);
455 }
456
457 private void agentDisconnect() {
458 if (mNetworkInfo.isConnected()) {
459 agentDisconnect(mNetworkInfo, mNetworkAgent);
460 mNetworkAgent = null;
461 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700462 }
463
464 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700465 * Establish a VPN network and return the file descriptor of the VPN
466 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700467 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700468 *
469 * @param config The parameters to configure the network.
470 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700471 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700472 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700473 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700474 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400475 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700476 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700477 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700478 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700479 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
480 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700481 long token = Binder.clearCallingIdentity();
482 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700483 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400484 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400485 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700486 throw new SecurityException("Restricted users cannot establish VPNs");
487 }
488
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700489 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400490 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700491 if (info == null) {
492 throw new SecurityException("Cannot find " + config.user);
493 }
494 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
495 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
496 }
497 } catch (RemoteException e) {
498 throw new SecurityException("Cannot find " + config.user);
499 } finally {
500 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700501 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700502
Chad Brubaker850eb672014-03-21 21:02:47 +0000503 // Save the old config in case we need to go back.
504 VpnConfig oldConfig = mConfig;
505 String oldInterface = mInterface;
506 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400507 NetworkAgent oldNetworkAgent = mNetworkAgent;
508 mNetworkAgent = null;
509 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000510
Chia-chi Yehe9107902011-07-02 01:48:50 -0700511 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700512 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700513 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700514 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700515 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700516
Chad Brubakerc2865192013-07-10 14:46:23 -0700517 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700518 StringBuilder builder = new StringBuilder();
519 for (LinkAddress address : config.addresses) {
520 builder.append(" " + address);
521 }
522 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700523 throw new IllegalArgumentException("At least one address must be specified");
524 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700525 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700526 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400527 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700528 throw new IllegalStateException("Cannot bind " + config.user);
529 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000530
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700531 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700532 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700533
534 // Fill more values.
535 config.user = mPackage;
536 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700537 config.startTime = SystemClock.elapsedRealtime();
538 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000539
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700540 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400541 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700542
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400543 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000544
545 if (oldConnection != null) {
546 mContext.unbindService(oldConnection);
547 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 // Remove the old tun's user forwarding rules
549 // The new tun's user rules have already been added so they will take over
550 // as rules are deleted. This prevents data leakage as the rules are moved over.
551 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000552 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000553 jniReset(oldInterface);
554 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700555
556 try {
557 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
558 } catch (IOException e) {
559 throw new IllegalStateException(
560 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
561 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000562 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400564 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000565 // restore old state
566 mConfig = oldConfig;
567 mConnection = oldConnection;
568 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 mInterface = oldInterface;
571 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700572 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000573 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700574 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700575 }
576
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800578 return mNetworkAgent != null && mInterface != null;
579 }
580
581 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
582 // that a call to mutate VPN state is admissible.
583 private boolean isCallerEstablishedOwnerLocked() {
584 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700585 }
586
Paul Jensen0784eea2014-08-19 16:00:24 -0400587 // Note: Return type guarantees results are deduped and sorted, which callers require.
588 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
589 SortedSet<Integer> uids = new TreeSet<Integer>();
590 for (String app : packageNames) {
591 int uid = getAppUid(app, userHandle);
592 if (uid != -1) uids.add(uid);
593 }
594 return uids;
595 }
596
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400597 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400598 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800599 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700600 throw new IllegalStateException("VPN is not active");
601 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700602
Paul Jensen0784eea2014-08-19 16:00:24 -0400603 if (mConfig.allowedApplications != null) {
604 // Add ranges covering all UIDs for allowedApplications.
605 int start = -1, stop = -1;
606 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
607 if (start == -1) {
608 start = uid;
609 } else if (uid != stop + 1) {
610 mVpnUsers.add(new UidRange(start, stop));
611 start = uid;
612 }
613 stop = uid;
614 }
615 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
616 } else if (mConfig.disallowedApplications != null) {
617 // Add all ranges for user skipping UIDs for disallowedApplications.
618 final UidRange userRange = UidRange.createForUser(userHandle);
619 int start = userRange.start;
620 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
621 if (uid == start) {
622 start++;
623 } else {
624 mVpnUsers.add(new UidRange(start, uid - 1));
625 start = uid + 1;
626 }
627 }
628 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
629 } else {
630 // Add all UIDs for the user.
631 mVpnUsers.add(UidRange.createForUser(userHandle));
632 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700633
634 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700635 }
636
Paul Jensen0784eea2014-08-19 16:00:24 -0400637 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
638 // apply to userHandle.
639 private List<UidRange> uidRangesForUser(int userHandle) {
640 final UidRange userRange = UidRange.createForUser(userHandle);
641 final List<UidRange> ranges = new ArrayList<UidRange>();
642 for (UidRange range : mVpnUsers) {
643 if (range.start >= userRange.start && range.stop <= userRange.stop) {
644 ranges.add(range);
645 }
646 }
647 return ranges;
648 }
649
650 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800651 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700652 throw new IllegalStateException("VPN is not active");
653 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400654 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700655 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400656 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700657 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400658 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700659 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700660 }
661
Paul Jensen0784eea2014-08-19 16:00:24 -0400662 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700663 // If the user is restricted tie them to the owner's VPN
664 synchronized(Vpn.this) {
665 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400666 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700667 if (user.isRestricted()) {
668 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400669 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400670 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400671 final List<UidRange> ranges = uidRangesForUser(userHandle);
672 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400673 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700674 } catch (Exception e) {
675 Log.wtf(TAG, "Failed to add restricted user to owner", e);
676 }
677 }
678 }
679 }
680
Paul Jensen0784eea2014-08-19 16:00:24 -0400681 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700682 // clean up if restricted
683 synchronized(Vpn.this) {
684 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400685 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700686 if (user.isRestricted()) {
687 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400688 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700689 } catch (Exception e) {
690 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
691 }
692 }
693 }
694 }
695
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700696 /**
697 * Return the configuration of the currently running VPN.
698 */
699 public VpnConfig getVpnConfig() {
700 enforceControlPermission();
701 return mConfig;
702 }
703
Jeff Sharkey899223b2012-08-04 15:24:58 -0700704 @Deprecated
705 public synchronized void interfaceStatusChanged(String iface, boolean up) {
706 try {
707 mObserver.interfaceStatusChanged(iface, up);
708 } catch (RemoteException e) {
709 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700710 }
711 }
712
Jeff Sharkey899223b2012-08-04 15:24:58 -0700713 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
714 @Override
715 public void interfaceStatusChanged(String interfaze, boolean up) {
716 synchronized (Vpn.this) {
717 if (!up && mLegacyVpnRunner != null) {
718 mLegacyVpnRunner.check(interfaze);
719 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700720 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700721 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700722
Jeff Sharkey899223b2012-08-04 15:24:58 -0700723 @Override
724 public void interfaceRemoved(String interfaze) {
725 synchronized (Vpn.this) {
726 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700727 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400728 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 mInterface = null;
730 if (mConnection != null) {
731 mContext.unbindService(mConnection);
732 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400733 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700734 } else if (mLegacyVpnRunner != null) {
735 mLegacyVpnRunner.exit();
736 mLegacyVpnRunner = null;
737 }
738 }
739 }
740 }
741 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700742
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700743 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800744 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700745 }
746
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700747 private class Connection implements ServiceConnection {
748 private IBinder mService;
749
750 @Override
751 public void onServiceConnected(ComponentName name, IBinder service) {
752 mService = service;
753 }
754
755 @Override
756 public void onServiceDisconnected(ComponentName name) {
757 mService = null;
758 }
759 }
760
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700761 private void prepareStatusIntent() {
762 final long token = Binder.clearCallingIdentity();
763 try {
764 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
765 } finally {
766 Binder.restoreCallingIdentity(token);
767 }
768 }
769
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700770 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800771 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700772 return false;
773 }
774 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800775 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700776 return success;
777 }
778
779 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800780 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700781 return false;
782 }
783 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800784 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700785 return success;
786 }
787
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800788 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
789 if (!isCallerEstablishedOwnerLocked()) {
790 return false;
791 }
792 if (networks == null) {
793 mConfig.underlyingNetworks = null;
794 } else {
795 mConfig.underlyingNetworks = new Network[networks.length];
796 for (int i = 0; i < networks.length; ++i) {
797 if (networks[i] == null) {
798 mConfig.underlyingNetworks[i] = null;
799 } else {
800 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
801 }
802 }
803 }
804 return true;
805 }
806
807 public synchronized Network[] getUnderlyingNetworks() {
808 if (!isRunningLocked()) {
809 return null;
810 }
811 return mConfig.underlyingNetworks;
812 }
813
814 public synchronized boolean appliesToUid(int uid) {
815 if (!isRunningLocked()) {
816 return false;
817 }
818 for (UidRange uidRange : mVpnUsers) {
819 if (uidRange.start <= uid && uid <= uidRange.stop) {
820 return true;
821 }
822 }
823 return false;
824 }
825
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700826 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700827 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700828 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700829 private native void jniReset(String interfaze);
830 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700831 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
832 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700833
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900834 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
835 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700836 // Currently legacy VPN only works on IPv4.
837 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900838 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700839 }
840 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700841
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900842 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700843 }
844
845 /**
846 * Start legacy VPN, controlling native daemons as needed. Creates a
847 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800848 *
849 * Should only be called to respond to Binder requests as this enforces caller permission. Use
850 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
851 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700852 */
853 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800854 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800855 long token = Binder.clearCallingIdentity();
856 try {
857 startLegacyVpnPrivileged(profile, keyStore, egress);
858 } finally {
859 Binder.restoreCallingIdentity(token);
860 }
861 }
862
863 /**
864 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
865 * permissions under the assumption that the caller is the system.
866 *
867 * Callers are responsible for checking permissions if needed.
868 */
869 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
870 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800871 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700872 throw new IllegalStateException("KeyStore isn't unlocked");
873 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400874 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400875 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400876 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
877 throw new SecurityException("Restricted users cannot establish VPNs");
878 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700879
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900880 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
881 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
882 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700883
884 // Load certificates.
885 String privateKey = "";
886 String userCert = "";
887 String caCert = "";
888 String serverCert = "";
889 if (!profile.ipsecUserCert.isEmpty()) {
890 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
891 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700892 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700893 }
894 if (!profile.ipsecCaCert.isEmpty()) {
895 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700896 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700897 }
898 if (!profile.ipsecServerCert.isEmpty()) {
899 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700900 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700901 }
902 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
903 throw new IllegalStateException("Cannot load credentials");
904 }
905
906 // Prepare arguments for racoon.
907 String[] racoon = null;
908 switch (profile.type) {
909 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
910 racoon = new String[] {
911 iface, profile.server, "udppsk", profile.ipsecIdentifier,
912 profile.ipsecSecret, "1701",
913 };
914 break;
915 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
916 racoon = new String[] {
917 iface, profile.server, "udprsa", privateKey, userCert,
918 caCert, serverCert, "1701",
919 };
920 break;
921 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
922 racoon = new String[] {
923 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
924 profile.ipsecSecret, profile.username, profile.password, "", gateway,
925 };
926 break;
927 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
928 racoon = new String[] {
929 iface, profile.server, "xauthrsa", privateKey, userCert,
930 caCert, serverCert, profile.username, profile.password, "", gateway,
931 };
932 break;
933 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
934 racoon = new String[] {
935 iface, profile.server, "hybridrsa",
936 caCert, serverCert, profile.username, profile.password, "", gateway,
937 };
938 break;
939 }
940
941 // Prepare arguments for mtpd.
942 String[] mtpd = null;
943 switch (profile.type) {
944 case VpnProfile.TYPE_PPTP:
945 mtpd = new String[] {
946 iface, "pptp", profile.server, "1723",
947 "name", profile.username, "password", profile.password,
948 "linkname", "vpn", "refuse-eap", "nodefaultroute",
949 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
950 (profile.mppe ? "+mppe" : "nomppe"),
951 };
952 break;
953 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
954 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
955 mtpd = new String[] {
956 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
957 "name", profile.username, "password", profile.password,
958 "linkname", "vpn", "refuse-eap", "nodefaultroute",
959 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
960 };
961 break;
962 }
963
964 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700965 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700966 config.user = profile.key;
967 config.interfaze = iface;
968 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700969
970 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700971 if (!profile.dnsServers.isEmpty()) {
972 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
973 }
974 if (!profile.searchDomains.isEmpty()) {
975 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
976 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700977 startLegacyVpn(config, racoon, mtpd);
978 }
979
980 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800981 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700982
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800983 // Prepare for the new request.
984 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700985 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700986
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700987 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700988 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
989 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700990 }
991
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800992 /** Stop legacy VPN. Permissions must be checked by callers. */
993 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700994 if (mLegacyVpnRunner != null) {
995 mLegacyVpnRunner.exit();
996 mLegacyVpnRunner = null;
997
998 synchronized (LegacyVpnRunner.TAG) {
999 // wait for old thread to completely finish before spinning up
1000 // new instance, otherwise state updates can be out of order.
1001 }
1002 }
1003 }
1004
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001005 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001006 * Return the information of the current ongoing legacy VPN.
1007 */
1008 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001009 // Check if the caller is authorized.
1010 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001011 if (mLegacyVpnRunner == null) return null;
1012
1013 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001014 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001015 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001016 if (mNetworkInfo.isConnected()) {
1017 info.intent = mStatusIntent;
1018 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001019 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001020 }
1021
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001022 public VpnConfig getLegacyVpnConfig() {
1023 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001024 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001025 } else {
1026 return null;
1027 }
1028 }
1029
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001030 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001031 * Bringing up a VPN connection takes time, and that is all this thread
1032 * does. Here we have plenty of time. The only thing we need to take
1033 * care of is responding to interruptions as soon as possible. Otherwise
1034 * requests will be piled up. This can be done in a Handler as a state
1035 * machine, but it is much easier to read in the current form.
1036 */
1037 private class LegacyVpnRunner extends Thread {
1038 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001039
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001040 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001041 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001042 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001043 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001044 private final AtomicInteger mOuterConnection =
1045 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001046
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001047 private long mTimer = -1;
1048
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001049 /**
1050 * Watch for the outer connection (passing in the constructor) going away.
1051 */
1052 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1053 @Override
1054 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001055 if (!mEnableTeardown) return;
1056
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001057 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1058 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1059 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1060 NetworkInfo info = (NetworkInfo)intent.getExtra(
1061 ConnectivityManager.EXTRA_NETWORK_INFO);
1062 if (info != null && !info.isConnectedOrConnecting()) {
1063 try {
1064 mObserver.interfaceStatusChanged(mOuterInterface, false);
1065 } catch (RemoteException e) {}
1066 }
1067 }
1068 }
1069 }
1070 };
1071
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001072 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001073 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001074 mConfig = config;
1075 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001076 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001077 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001078 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001079
1080 // This is the interface which VPN is running on,
1081 // mConfig.interfaze will change to point to OUR
1082 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001083 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001084 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001085 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001086 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001087
Paul Jensene75b9e32015-04-06 11:54:53 -04001088 if (!TextUtils.isEmpty(mOuterInterface)) {
1089 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1090 for (Network network : cm.getAllNetworks()) {
1091 final LinkProperties lp = cm.getLinkProperties(network);
1092 if (lp != null && mOuterInterface.equals(lp.getInterfaceName())) {
1093 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1094 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1095 }
1096 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001097 }
1098
1099 IntentFilter filter = new IntentFilter();
1100 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1101 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001102 }
1103
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001104 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001105 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001106 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1107 exit();
1108 }
1109 }
1110
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001111 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001112 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001113 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001114 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001115 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001116 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001117 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001118 try {
1119 mContext.unregisterReceiver(mBroadcastReceiver);
1120 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001121 }
1122
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001123 @Override
1124 public void run() {
1125 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001126 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001127 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001128 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001129 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001130 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001131 }
1132 }
1133
1134 private void checkpoint(boolean yield) throws InterruptedException {
1135 long now = SystemClock.elapsedRealtime();
1136 if (mTimer == -1) {
1137 mTimer = now;
1138 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001139 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001140 Thread.sleep(yield ? 200 : 1);
1141 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001142 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001143 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001144 }
1145 }
1146
1147 private void execute() {
1148 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001149 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001150 try {
1151 // Initialize the timer.
1152 checkpoint(false);
1153
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001154 // Wait for the daemons to stop.
1155 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001156 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001157 checkpoint(true);
1158 }
1159 }
1160
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001161 // Clear the previous state.
1162 File state = new File("/data/misc/vpn/state");
1163 state.delete();
1164 if (state.exists()) {
1165 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001166 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001167 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001168 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001169
Chia-chi Yehe9107902011-07-02 01:48:50 -07001170 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001171 boolean restart = false;
1172 for (String[] arguments : mArguments) {
1173 restart = restart || (arguments != null);
1174 }
1175 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001176 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001177 return;
1178 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001179 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001180
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001181 // Start the daemon with arguments.
1182 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 String[] arguments = mArguments[i];
1184 if (arguments == null) {
1185 continue;
1186 }
1187
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001188 // Start the daemon.
1189 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001190 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001191
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001192 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001193 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001194 checkpoint(true);
1195 }
1196
1197 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001198 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001199 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001200 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001201
1202 // Wait for the socket to connect.
1203 while (true) {
1204 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001205 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001206 break;
1207 } catch (Exception e) {
1208 // ignore
1209 }
1210 checkpoint(true);
1211 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001212 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001213
1214 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001215 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001216 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001217 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001218 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001219 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001220 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001221 out.write(bytes.length >> 8);
1222 out.write(bytes.length);
1223 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001224 checkpoint(false);
1225 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001226 out.write(0xFF);
1227 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001228 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001229
1230 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001231 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001232 while (true) {
1233 try {
1234 if (in.read() == -1) {
1235 break;
1236 }
1237 } catch (Exception e) {
1238 // ignore
1239 }
1240 checkpoint(true);
1241 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001242 }
1243
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001244 // Wait for the daemons to create the new state.
1245 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001246 // Check if a running daemon is dead.
1247 for (int i = 0; i < mDaemons.length; ++i) {
1248 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001249 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001250 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001251 }
1252 }
1253 checkpoint(true);
1254 }
1255
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001256 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001257 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001258 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001259 throw new IllegalStateException("Cannot parse the state");
1260 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001261
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001262 // Set the interface and the addresses in the config.
1263 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001264
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001265 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001266 // Set the routes if they are not set in the config.
1267 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001268 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001269 }
1270
1271 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001272 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001273 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001274 if (!dnsServers.isEmpty()) {
1275 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1276 }
1277 }
1278
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001279 // Set the search domains if they are not set in the config.
1280 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1281 String searchDomains = parameters[4].trim();
1282 if (!searchDomains.isEmpty()) {
1283 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1284 }
1285 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001286
Lorenzo Colitti50262792014-09-19 01:53:35 +09001287 // Add a throw route for the VPN server endpoint, if one was specified.
1288 String endpoint = parameters[5];
1289 if (!endpoint.isEmpty()) {
1290 try {
1291 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1292 if (addr instanceof Inet4Address) {
1293 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1294 } else if (addr instanceof Inet6Address) {
1295 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1296 } else {
1297 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1298 }
1299 } catch (IllegalArgumentException e) {
1300 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1301 }
1302 }
1303
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001304 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001305 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001306 // Set the start time
1307 mConfig.startTime = SystemClock.elapsedRealtime();
1308
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001309 // Check if the thread is interrupted while we are waiting.
1310 checkpoint(false);
1311
Chia-chi Yehe9107902011-07-02 01:48:50 -07001312 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001313 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001314 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001315 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001316
1317 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001318 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001319 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001320
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001321 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001322
1323 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001324 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001325 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001326 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001327 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001328 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001329 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001330 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001331 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001332 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001333 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001334 }
1335 }
1336
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001337 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001338 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001339 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001340 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001341 }
1342 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001343
1344 /**
1345 * Monitor the daemons we started, moving to disconnected state if the
1346 * underlying services fail.
1347 */
1348 private void monitorDaemons() {
1349 if (!mNetworkInfo.isConnected()) {
1350 return;
1351 }
1352
1353 try {
1354 while (true) {
1355 Thread.sleep(2000);
1356 for (int i = 0; i < mDaemons.length; i++) {
1357 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1358 return;
1359 }
1360 }
1361 }
1362 } catch (InterruptedException e) {
1363 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1364 } finally {
1365 for (String daemon : mDaemons) {
1366 SystemService.stop(daemon);
1367 }
1368
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001369 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001370 }
1371 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001372 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001373}