blob: 7f47678d4f2fc9d09c1aab3ded9f073903f69482 [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;
Lorenzo Colitti50262792014-09-19 01:53:35 +090020import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090021import static android.net.RouteInfo.RTN_UNREACHABLE;
Jeff Davidsonbc19c182014-11-11 13:20:01 -080022import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070023import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070024import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070025import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070026import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070027import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070028import android.content.Context;
29import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070030import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070031import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070032import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040033import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070035import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070036import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070037import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070038import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090039import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070040import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070041import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070042import android.net.LocalSocket;
43import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080044import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040045import android.net.NetworkAgent;
46import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040048import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070049import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070050import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040051import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070052import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080053import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070054import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070055import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040056import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070057import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070058import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070059import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070060import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070061import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070062import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070063import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070064import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070065import android.security.Credentials;
66import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070067import android.util.Log;
68
Chad Brubakerc2865192013-07-10 14:46:23 -070069import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080072import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070073import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070074import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070075
Jeff Davidson05542602014-08-11 14:07:27 -070076import libcore.io.IoUtils;
77
Chia-chi Yeh97a61562011-07-14 15:05:05 -070078import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070079import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070080import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070081import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070082import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070083import java.net.Inet6Address;
84import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070085import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040086import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070087import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040088import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040089import java.util.SortedSet;
90import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070091import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070092
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093/**
94 * @hide
95 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040096public class Vpn {
97 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -070098 private static final String TAG = "Vpn";
99 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400100
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 // TODO: create separate trackers for each unique VPN to support
102 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700103
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104 private Context mContext;
105 private NetworkInfo mNetworkInfo;
106 private String mPackage;
107 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700108 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700109 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700110 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700111 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700112 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700113 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400114 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700115 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400116 private NetworkAgent mNetworkAgent;
117 private final Looper mLooper;
118 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700119
120 /* list of users using this VPN. */
121 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400122 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700123 private BroadcastReceiver mUserIntentReceiver = null;
124
Paul Jensen0784eea2014-08-19 16:00:24 -0400125 // Handle of user initiating VPN.
126 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400129 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700132 mConnService = connService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400133 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mLooper = looper;
135
136 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400137 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700138
139 try {
140 netService.registerObserver(mObserver);
141 } catch (RemoteException e) {
142 Log.wtf(TAG, "Problem registering observer", e);
143 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400144 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700145 // Owner's VPN also needs to handle restricted users
146 mUserIntentReceiver = new BroadcastReceiver() {
147 @Override
148 public void onReceive(Context context, Intent intent) {
149 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400150 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700151 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400152 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700153
154 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700156 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400157 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700158 }
159 }
160 };
161
162 IntentFilter intentFilter = new IntentFilter();
163 intentFilter.addAction(Intent.ACTION_USER_ADDED);
164 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
165 mContext.registerReceiverAsUser(
166 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
167 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400168
169 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
170 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
171 mNetworkCapabilities = new NetworkCapabilities();
172 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
173 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 }
175
Jeff Sharkey57666932013-04-30 17:01:57 -0700176 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700177 * Set if this object is responsible for watching for {@link NetworkInfo}
178 * teardown. When {@code false}, teardown is handled externally by someone
179 * else.
180 */
181 public void setEnableTeardown(boolean enableTeardown) {
182 mEnableTeardown = enableTeardown;
183 }
184
Jeff Sharkey899223b2012-08-04 15:24:58 -0700185 /**
186 * Update current state, dispaching event to listeners.
187 */
188 private void updateState(DetailedState detailedState, String reason) {
189 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
190 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400191 if (mNetworkAgent != null) {
192 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
193 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700194 }
195
196 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700197 * Prepare for a VPN application. This method is designed to solve
198 * race conditions. It first compares the current prepared package
199 * with {@code oldPackage}. If they are the same, the prepared
200 * package is revoked and replaced with {@code newPackage}. If
201 * {@code oldPackage} is {@code null}, the comparison is omitted.
202 * If {@code newPackage} is the same package or {@code null}, the
203 * revocation is omitted. This method returns {@code true} if the
204 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700205 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700206 * Legacy VPN is handled specially since it is not a real package.
207 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
208 * it can be revoked by itself.
209 *
210 * @param oldPackage The package name of the old VPN application.
211 * @param newPackage The package name of the new VPN application.
212 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700213 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700214 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidsonbe085872014-10-24 10:35:53 -0700215 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800216 // The package doesn't match. We return false (to obtain user consent) unless the user
217 // has already consented to that VPN package.
Jeff Davidson05542602014-08-11 14:07:27 -0700218 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
Jeff Davidson11008a72014-11-20 13:12:46 -0800219 prepareInternal(oldPackage);
Jeff Davidson05542602014-08-11 14:07:27 -0700220 return true;
221 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700222 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700223 }
224
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700225 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700226 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
227 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700228 return true;
229 }
230
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700231 // Check if the caller is authorized.
232 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700233
Jeff Davidson11008a72014-11-20 13:12:46 -0800234 prepareInternal(newPackage);
235 return true;
236 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700237
Jeff Davidson11008a72014-11-20 13:12:46 -0800238 /** Prepare the VPN for the given package. Does not perform permission checks. */
239 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400240 long token = Binder.clearCallingIdentity();
241 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800242 // Reset the interface.
243 if (mInterface != null) {
244 mStatusIntent = null;
245 agentDisconnect();
246 jniReset(mInterface);
247 mInterface = null;
248 mVpnUsers = null;
249 }
250
251 // Revoke the connection or stop LegacyVpnRunner.
252 if (mConnection != null) {
253 try {
254 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
255 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
256 } catch (Exception e) {
257 // ignore
258 }
259 mContext.unbindService(mConnection);
260 mConnection = null;
261 } else if (mLegacyVpnRunner != null) {
262 mLegacyVpnRunner.exit();
263 mLegacyVpnRunner = null;
264 }
265
266 try {
267 mNetd.denyProtect(mOwnerUID);
268 } catch (Exception e) {
269 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
270 }
271
272 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
273 mPackage = newPackage;
274 mOwnerUID = getAppUid(newPackage, mUserHandle);
275 try {
276 mNetd.allowProtect(mOwnerUID);
277 } catch (Exception e) {
278 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
279 }
280 mConfig = null;
281
282 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400283 } finally {
284 Binder.restoreCallingIdentity(token);
285 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700286 }
287
Jeff Davidson05542602014-08-11 14:07:27 -0700288 /**
289 * Set whether the current package has the ability to launch VPNs without user intervention.
290 */
291 public void setPackageAuthorization(boolean authorized) {
292 // Check if the caller is authorized.
293 enforceControlPermission();
294
295 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
296 return;
297 }
298
299 long token = Binder.clearCallingIdentity();
300 try {
301 AppOpsManager appOps =
302 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
303 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
304 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
305 } catch (Exception e) {
306 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
307 } finally {
308 Binder.restoreCallingIdentity(token);
309 }
310 }
311
312 private boolean isVpnUserPreConsented(String packageName) {
313 AppOpsManager appOps =
314 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
315
316 // Verify that the caller matches the given package and has permission to activate VPNs.
317 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
318 packageName) == AppOpsManager.MODE_ALLOWED;
319 }
320
Paul Jensen0784eea2014-08-19 16:00:24 -0400321 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700322 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400323 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700324 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400325 PackageManager pm = mContext.getPackageManager();
326 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700327 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400328 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400329 } catch (NameNotFoundException e) {
330 result = -1;
331 }
332 return result;
333 }
334
335 public NetworkInfo getNetworkInfo() {
336 return mNetworkInfo;
337 }
338
Lorenzo Colitti60446162014-09-20 00:14:31 +0900339 private LinkProperties makeLinkProperties() {
340 boolean allowIPv4 = mConfig.allowIPv4;
341 boolean allowIPv6 = mConfig.allowIPv6;
342
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400343 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900344
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400345 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700346
Lorenzo Colitti60446162014-09-20 00:14:31 +0900347 if (mConfig.addresses != null) {
348 for (LinkAddress address : mConfig.addresses) {
349 lp.addLinkAddress(address);
350 allowIPv4 |= address.getAddress() instanceof Inet4Address;
351 allowIPv6 |= address.getAddress() instanceof Inet6Address;
352 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400353 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900354
355 if (mConfig.routes != null) {
356 for (RouteInfo route : mConfig.routes) {
357 lp.addRoute(route);
358 InetAddress address = route.getDestination().getAddress();
359 allowIPv4 |= address instanceof Inet4Address;
360 allowIPv6 |= address instanceof Inet6Address;
361 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400362 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700363
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400364 if (mConfig.dnsServers != null) {
365 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700366 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
367 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900368 allowIPv4 |= address instanceof Inet4Address;
369 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400370 }
371 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700372
Lorenzo Colitti60446162014-09-20 00:14:31 +0900373 if (!allowIPv4) {
374 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
375 }
376 if (!allowIPv6) {
377 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
378 }
379
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400380 // Concatenate search domains into a string.
381 StringBuilder buffer = new StringBuilder();
382 if (mConfig.searchDomains != null) {
383 for (String domain : mConfig.searchDomains) {
384 buffer.append(domain).append(' ');
385 }
386 }
387 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700388
Lorenzo Colitti60446162014-09-20 00:14:31 +0900389 // TODO: Stop setting the MTU in jniCreate and set it here.
390
391 return lp;
392 }
393
394 private void agentConnect() {
395 LinkProperties lp = makeLinkProperties();
396
397 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
398 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
399 } else {
400 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
401 }
402
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400403 mNetworkInfo.setIsAvailable(true);
404 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700405
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700406 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700407 networkMisc.allowBypass = mConfig.allowBypass;
408
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400409 long token = Binder.clearCallingIdentity();
410 try {
411 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700412 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700413 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400414 public void unwanted() {
415 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700416 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400417 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700418 } finally {
419 Binder.restoreCallingIdentity(token);
420 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700421
Paul Jensen0784eea2014-08-19 16:00:24 -0400422 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400423 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400424 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400425 token = Binder.clearCallingIdentity();
426 List<UserInfo> users;
427 try {
428 users = UserManager.get(mContext).getUsers();
429 } finally {
430 Binder.restoreCallingIdentity(token);
431 }
432 for (UserInfo user : users) {
433 if (user.isRestricted()) {
434 addVpnUserLocked(user.id);
435 }
436 }
437 }
438 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
439 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700440
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400441 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
442 networkInfo.setIsAvailable(false);
443 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
444 if (networkAgent != null) {
445 networkAgent.sendNetworkInfo(networkInfo);
446 }
447 }
448
449 private void agentDisconnect(NetworkAgent networkAgent) {
450 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
451 agentDisconnect(networkInfo, networkAgent);
452 }
453
454 private void agentDisconnect() {
455 if (mNetworkInfo.isConnected()) {
456 agentDisconnect(mNetworkInfo, mNetworkAgent);
457 mNetworkAgent = null;
458 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700459 }
460
461 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700462 * Establish a VPN network and return the file descriptor of the VPN
463 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700464 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700465 *
466 * @param config The parameters to configure the network.
467 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700468 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700469 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700470 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700471 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400472 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700473 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700474 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700475 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700476 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
477 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700478 long token = Binder.clearCallingIdentity();
479 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700480 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400481 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400482 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700483 throw new SecurityException("Restricted users cannot establish VPNs");
484 }
485
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700486 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400487 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700488 if (info == null) {
489 throw new SecurityException("Cannot find " + config.user);
490 }
491 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
492 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
493 }
494 } catch (RemoteException e) {
495 throw new SecurityException("Cannot find " + config.user);
496 } finally {
497 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700498 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700499
Chad Brubaker850eb672014-03-21 21:02:47 +0000500 // Save the old config in case we need to go back.
501 VpnConfig oldConfig = mConfig;
502 String oldInterface = mInterface;
503 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400504 NetworkAgent oldNetworkAgent = mNetworkAgent;
505 mNetworkAgent = null;
506 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000507
Chia-chi Yehe9107902011-07-02 01:48:50 -0700508 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700509 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700510 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700511 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700512 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700513
Chad Brubakerc2865192013-07-10 14:46:23 -0700514 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700515 StringBuilder builder = new StringBuilder();
516 for (LinkAddress address : config.addresses) {
517 builder.append(" " + address);
518 }
519 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700520 throw new IllegalArgumentException("At least one address must be specified");
521 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700522 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700523 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400524 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700525 throw new IllegalStateException("Cannot bind " + config.user);
526 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000527
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700528 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700529 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700530
531 // Fill more values.
532 config.user = mPackage;
533 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700534 config.startTime = SystemClock.elapsedRealtime();
535 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000536
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700537 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400538 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700539
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400540 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000541
542 if (oldConnection != null) {
543 mContext.unbindService(oldConnection);
544 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400545 // Remove the old tun's user forwarding rules
546 // The new tun's user rules have already been added so they will take over
547 // as rules are deleted. This prevents data leakage as the rules are moved over.
548 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000549 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000550 jniReset(oldInterface);
551 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700552
553 try {
554 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
555 } catch (IOException e) {
556 throw new IllegalStateException(
557 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
558 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000559 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000560 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400561 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000562 // restore old state
563 mConfig = oldConfig;
564 mConnection = oldConnection;
565 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400566 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000567 mInterface = oldInterface;
568 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700569 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700571 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700572 }
573
Chad Brubakerc2865192013-07-10 14:46:23 -0700574 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800575 return mNetworkAgent != null && mInterface != null;
576 }
577
578 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
579 // that a call to mutate VPN state is admissible.
580 private boolean isCallerEstablishedOwnerLocked() {
581 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700582 }
583
Paul Jensen0784eea2014-08-19 16:00:24 -0400584 // Note: Return type guarantees results are deduped and sorted, which callers require.
585 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
586 SortedSet<Integer> uids = new TreeSet<Integer>();
587 for (String app : packageNames) {
588 int uid = getAppUid(app, userHandle);
589 if (uid != -1) uids.add(uid);
590 }
591 return uids;
592 }
593
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400594 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400595 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800596 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700597 throw new IllegalStateException("VPN is not active");
598 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700599
Paul Jensen0784eea2014-08-19 16:00:24 -0400600 if (mConfig.allowedApplications != null) {
601 // Add ranges covering all UIDs for allowedApplications.
602 int start = -1, stop = -1;
603 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
604 if (start == -1) {
605 start = uid;
606 } else if (uid != stop + 1) {
607 mVpnUsers.add(new UidRange(start, stop));
608 start = uid;
609 }
610 stop = uid;
611 }
612 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
613 } else if (mConfig.disallowedApplications != null) {
614 // Add all ranges for user skipping UIDs for disallowedApplications.
615 final UidRange userRange = UidRange.createForUser(userHandle);
616 int start = userRange.start;
617 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
618 if (uid == start) {
619 start++;
620 } else {
621 mVpnUsers.add(new UidRange(start, uid - 1));
622 start = uid + 1;
623 }
624 }
625 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
626 } else {
627 // Add all UIDs for the user.
628 mVpnUsers.add(UidRange.createForUser(userHandle));
629 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700630
631 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700632 }
633
Paul Jensen0784eea2014-08-19 16:00:24 -0400634 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
635 // apply to userHandle.
636 private List<UidRange> uidRangesForUser(int userHandle) {
637 final UidRange userRange = UidRange.createForUser(userHandle);
638 final List<UidRange> ranges = new ArrayList<UidRange>();
639 for (UidRange range : mVpnUsers) {
640 if (range.start >= userRange.start && range.stop <= userRange.stop) {
641 ranges.add(range);
642 }
643 }
644 return ranges;
645 }
646
647 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800648 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700649 throw new IllegalStateException("VPN is not active");
650 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400651 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700652 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400653 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700654 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400655 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700656 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700657 }
658
Paul Jensen0784eea2014-08-19 16:00:24 -0400659 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700660 // If the user is restricted tie them to the owner's VPN
661 synchronized(Vpn.this) {
662 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400663 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700664 if (user.isRestricted()) {
665 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400666 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400667 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400668 final List<UidRange> ranges = uidRangesForUser(userHandle);
669 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400670 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700671 } catch (Exception e) {
672 Log.wtf(TAG, "Failed to add restricted user to owner", e);
673 }
674 }
675 }
676 }
677
Paul Jensen0784eea2014-08-19 16:00:24 -0400678 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700679 // clean up if restricted
680 synchronized(Vpn.this) {
681 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400682 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700683 if (user.isRestricted()) {
684 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400685 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700686 } catch (Exception e) {
687 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
688 }
689 }
690 }
691 }
692
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700693 /**
694 * Return the configuration of the currently running VPN.
695 */
696 public VpnConfig getVpnConfig() {
697 enforceControlPermission();
698 return mConfig;
699 }
700
Jeff Sharkey899223b2012-08-04 15:24:58 -0700701 @Deprecated
702 public synchronized void interfaceStatusChanged(String iface, boolean up) {
703 try {
704 mObserver.interfaceStatusChanged(iface, up);
705 } catch (RemoteException e) {
706 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700707 }
708 }
709
Jeff Sharkey899223b2012-08-04 15:24:58 -0700710 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
711 @Override
712 public void interfaceStatusChanged(String interfaze, boolean up) {
713 synchronized (Vpn.this) {
714 if (!up && mLegacyVpnRunner != null) {
715 mLegacyVpnRunner.check(interfaze);
716 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700717 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700718 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700719
Jeff Sharkey899223b2012-08-04 15:24:58 -0700720 @Override
721 public void interfaceRemoved(String interfaze) {
722 synchronized (Vpn.this) {
723 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700724 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400725 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500726 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700727 mInterface = null;
728 if (mConnection != null) {
729 mContext.unbindService(mConnection);
730 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400731 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700732 } else if (mLegacyVpnRunner != null) {
733 mLegacyVpnRunner.exit();
734 mLegacyVpnRunner = null;
735 }
736 }
737 }
738 }
739 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700740
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700741 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800742 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700743 }
744
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700745 private class Connection implements ServiceConnection {
746 private IBinder mService;
747
748 @Override
749 public void onServiceConnected(ComponentName name, IBinder service) {
750 mService = service;
751 }
752
753 @Override
754 public void onServiceDisconnected(ComponentName name) {
755 mService = null;
756 }
757 }
758
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700759 private void prepareStatusIntent() {
760 final long token = Binder.clearCallingIdentity();
761 try {
762 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
763 } finally {
764 Binder.restoreCallingIdentity(token);
765 }
766 }
767
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700768 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800769 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700770 return false;
771 }
772 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800773 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700774 return success;
775 }
776
777 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800778 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700779 return false;
780 }
781 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800782 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700783 return success;
784 }
785
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800786 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
787 if (!isCallerEstablishedOwnerLocked()) {
788 return false;
789 }
790 if (networks == null) {
791 mConfig.underlyingNetworks = null;
792 } else {
793 mConfig.underlyingNetworks = new Network[networks.length];
794 for (int i = 0; i < networks.length; ++i) {
795 if (networks[i] == null) {
796 mConfig.underlyingNetworks[i] = null;
797 } else {
798 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
799 }
800 }
801 }
802 return true;
803 }
804
805 public synchronized Network[] getUnderlyingNetworks() {
806 if (!isRunningLocked()) {
807 return null;
808 }
809 return mConfig.underlyingNetworks;
810 }
811
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800812 /**
813 * This method should only be called by ConnectivityService. Because it doesn't
814 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
815 */
816 public synchronized VpnInfo getVpnInfo() {
817 if (!isRunningLocked()) {
818 return null;
819 }
820
821 VpnInfo info = new VpnInfo();
822 info.ownerUid = mOwnerUID;
823 info.vpnIface = mInterface;
824 return info;
825 }
826
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800827 public synchronized boolean appliesToUid(int uid) {
828 if (!isRunningLocked()) {
829 return false;
830 }
831 for (UidRange uidRange : mVpnUsers) {
832 if (uidRange.start <= uid && uid <= uidRange.stop) {
833 return true;
834 }
835 }
836 return false;
837 }
838
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700839 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700840 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700841 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700842 private native void jniReset(String interfaze);
843 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700844 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
845 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700846
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900847 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
848 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700849 // Currently legacy VPN only works on IPv4.
850 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900851 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700852 }
853 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700854
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900855 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700856 }
857
858 /**
859 * Start legacy VPN, controlling native daemons as needed. Creates a
860 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800861 *
862 * Should only be called to respond to Binder requests as this enforces caller permission. Use
863 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
864 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700865 */
866 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800867 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800868 long token = Binder.clearCallingIdentity();
869 try {
870 startLegacyVpnPrivileged(profile, keyStore, egress);
871 } finally {
872 Binder.restoreCallingIdentity(token);
873 }
874 }
875
876 /**
877 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
878 * permissions under the assumption that the caller is the system.
879 *
880 * Callers are responsible for checking permissions if needed.
881 */
882 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
883 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800884 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700885 throw new IllegalStateException("KeyStore isn't unlocked");
886 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400887 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400888 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400889 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
890 throw new SecurityException("Restricted users cannot establish VPNs");
891 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700892
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900893 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
894 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
895 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700896
897 // Load certificates.
898 String privateKey = "";
899 String userCert = "";
900 String caCert = "";
901 String serverCert = "";
902 if (!profile.ipsecUserCert.isEmpty()) {
903 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
904 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700905 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700906 }
907 if (!profile.ipsecCaCert.isEmpty()) {
908 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700909 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700910 }
911 if (!profile.ipsecServerCert.isEmpty()) {
912 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700913 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700914 }
915 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
916 throw new IllegalStateException("Cannot load credentials");
917 }
918
919 // Prepare arguments for racoon.
920 String[] racoon = null;
921 switch (profile.type) {
922 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
923 racoon = new String[] {
924 iface, profile.server, "udppsk", profile.ipsecIdentifier,
925 profile.ipsecSecret, "1701",
926 };
927 break;
928 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
929 racoon = new String[] {
930 iface, profile.server, "udprsa", privateKey, userCert,
931 caCert, serverCert, "1701",
932 };
933 break;
934 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
935 racoon = new String[] {
936 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
937 profile.ipsecSecret, profile.username, profile.password, "", gateway,
938 };
939 break;
940 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
941 racoon = new String[] {
942 iface, profile.server, "xauthrsa", privateKey, userCert,
943 caCert, serverCert, profile.username, profile.password, "", gateway,
944 };
945 break;
946 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
947 racoon = new String[] {
948 iface, profile.server, "hybridrsa",
949 caCert, serverCert, profile.username, profile.password, "", gateway,
950 };
951 break;
952 }
953
954 // Prepare arguments for mtpd.
955 String[] mtpd = null;
956 switch (profile.type) {
957 case VpnProfile.TYPE_PPTP:
958 mtpd = new String[] {
959 iface, "pptp", profile.server, "1723",
960 "name", profile.username, "password", profile.password,
961 "linkname", "vpn", "refuse-eap", "nodefaultroute",
962 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
963 (profile.mppe ? "+mppe" : "nomppe"),
964 };
965 break;
966 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
967 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
968 mtpd = new String[] {
969 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
970 "name", profile.username, "password", profile.password,
971 "linkname", "vpn", "refuse-eap", "nodefaultroute",
972 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
973 };
974 break;
975 }
976
977 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700978 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700979 config.user = profile.key;
980 config.interfaze = iface;
981 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700982
983 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700984 if (!profile.dnsServers.isEmpty()) {
985 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
986 }
987 if (!profile.searchDomains.isEmpty()) {
988 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
989 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700990 startLegacyVpn(config, racoon, mtpd);
991 }
992
993 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800994 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700995
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800996 // Prepare for the new request.
997 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700998 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700999
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001000 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001001 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1002 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001003 }
1004
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001005 /** Stop legacy VPN. Permissions must be checked by callers. */
1006 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001007 if (mLegacyVpnRunner != null) {
1008 mLegacyVpnRunner.exit();
1009 mLegacyVpnRunner = null;
1010
1011 synchronized (LegacyVpnRunner.TAG) {
1012 // wait for old thread to completely finish before spinning up
1013 // new instance, otherwise state updates can be out of order.
1014 }
1015 }
1016 }
1017
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001018 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001019 * Return the information of the current ongoing legacy VPN.
1020 */
1021 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001022 // Check if the caller is authorized.
1023 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001024 if (mLegacyVpnRunner == null) return null;
1025
1026 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001027 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001028 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001029 if (mNetworkInfo.isConnected()) {
1030 info.intent = mStatusIntent;
1031 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001032 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001033 }
1034
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001035 public VpnConfig getLegacyVpnConfig() {
1036 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001037 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001038 } else {
1039 return null;
1040 }
1041 }
1042
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001043 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044 * Bringing up a VPN connection takes time, and that is all this thread
1045 * does. Here we have plenty of time. The only thing we need to take
1046 * care of is responding to interruptions as soon as possible. Otherwise
1047 * requests will be piled up. This can be done in a Handler as a state
1048 * machine, but it is much easier to read in the current form.
1049 */
1050 private class LegacyVpnRunner extends Thread {
1051 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001052
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001053 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001055 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001056 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001057 private final AtomicInteger mOuterConnection =
1058 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001059
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001060 private long mTimer = -1;
1061
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001062 /**
1063 * Watch for the outer connection (passing in the constructor) going away.
1064 */
1065 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1066 @Override
1067 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001068 if (!mEnableTeardown) return;
1069
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001070 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1071 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1072 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1073 NetworkInfo info = (NetworkInfo)intent.getExtra(
1074 ConnectivityManager.EXTRA_NETWORK_INFO);
1075 if (info != null && !info.isConnectedOrConnecting()) {
1076 try {
1077 mObserver.interfaceStatusChanged(mOuterInterface, false);
1078 } catch (RemoteException e) {}
1079 }
1080 }
1081 }
1082 }
1083 };
1084
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001085 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001086 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001087 mConfig = config;
1088 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001089 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001090 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001091 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001092
1093 // This is the interface which VPN is running on,
1094 // mConfig.interfaze will change to point to OUR
1095 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001096 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001097 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001098 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001099 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001100
1101 try {
1102 mOuterConnection.set(
1103 mConnService.findConnectionTypeForIface(mOuterInterface));
1104 } catch (Exception e) {
1105 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1106 }
1107
1108 IntentFilter filter = new IntentFilter();
1109 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1110 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001111 }
1112
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001113 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001114 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001115 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1116 exit();
1117 }
1118 }
1119
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001120 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001121 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001122 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001123 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001124 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001125 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001126 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001127 try {
1128 mContext.unregisterReceiver(mBroadcastReceiver);
1129 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001130 }
1131
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001132 @Override
1133 public void run() {
1134 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001135 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001136 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001137 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001138 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001139 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001140 }
1141 }
1142
1143 private void checkpoint(boolean yield) throws InterruptedException {
1144 long now = SystemClock.elapsedRealtime();
1145 if (mTimer == -1) {
1146 mTimer = now;
1147 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001148 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001149 Thread.sleep(yield ? 200 : 1);
1150 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001151 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001152 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001153 }
1154 }
1155
1156 private void execute() {
1157 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001158 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001159 try {
1160 // Initialize the timer.
1161 checkpoint(false);
1162
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001163 // Wait for the daemons to stop.
1164 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001165 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001166 checkpoint(true);
1167 }
1168 }
1169
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001170 // Clear the previous state.
1171 File state = new File("/data/misc/vpn/state");
1172 state.delete();
1173 if (state.exists()) {
1174 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001175 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001176 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001177 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001178
Chia-chi Yehe9107902011-07-02 01:48:50 -07001179 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001180 boolean restart = false;
1181 for (String[] arguments : mArguments) {
1182 restart = restart || (arguments != null);
1183 }
1184 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001185 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001186 return;
1187 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001188 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001189
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001190 // Start the daemon with arguments.
1191 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001192 String[] arguments = mArguments[i];
1193 if (arguments == null) {
1194 continue;
1195 }
1196
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001197 // Start the daemon.
1198 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001199 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001200
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001201 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001202 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001203 checkpoint(true);
1204 }
1205
1206 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001207 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001208 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001209 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001210
1211 // Wait for the socket to connect.
1212 while (true) {
1213 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001214 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001215 break;
1216 } catch (Exception e) {
1217 // ignore
1218 }
1219 checkpoint(true);
1220 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001221 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001222
1223 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001224 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001225 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001226 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001227 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001228 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001230 out.write(bytes.length >> 8);
1231 out.write(bytes.length);
1232 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001233 checkpoint(false);
1234 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001235 out.write(0xFF);
1236 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001237 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001238
1239 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001240 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001241 while (true) {
1242 try {
1243 if (in.read() == -1) {
1244 break;
1245 }
1246 } catch (Exception e) {
1247 // ignore
1248 }
1249 checkpoint(true);
1250 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001251 }
1252
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001253 // Wait for the daemons to create the new state.
1254 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001255 // Check if a running daemon is dead.
1256 for (int i = 0; i < mDaemons.length; ++i) {
1257 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001258 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001259 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001260 }
1261 }
1262 checkpoint(true);
1263 }
1264
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001265 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001266 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001267 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001268 throw new IllegalStateException("Cannot parse the state");
1269 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001270
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001271 // Set the interface and the addresses in the config.
1272 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001273
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001274 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001275 // Set the routes if they are not set in the config.
1276 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001277 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001278 }
1279
1280 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001281 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001282 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001283 if (!dnsServers.isEmpty()) {
1284 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1285 }
1286 }
1287
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001288 // Set the search domains if they are not set in the config.
1289 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1290 String searchDomains = parameters[4].trim();
1291 if (!searchDomains.isEmpty()) {
1292 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1293 }
1294 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001295
Lorenzo Colitti50262792014-09-19 01:53:35 +09001296 // Add a throw route for the VPN server endpoint, if one was specified.
1297 String endpoint = parameters[5];
1298 if (!endpoint.isEmpty()) {
1299 try {
1300 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1301 if (addr instanceof Inet4Address) {
1302 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1303 } else if (addr instanceof Inet6Address) {
1304 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1305 } else {
1306 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1307 }
1308 } catch (IllegalArgumentException e) {
1309 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1310 }
1311 }
1312
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001313 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001314 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001315 // Set the start time
1316 mConfig.startTime = SystemClock.elapsedRealtime();
1317
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001318 // Check if the thread is interrupted while we are waiting.
1319 checkpoint(false);
1320
Chia-chi Yehe9107902011-07-02 01:48:50 -07001321 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001322 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001323 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001324 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001325
1326 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001327 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001328 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001329
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001330 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001331
1332 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001333 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001334 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001335 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001336 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001337 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001338 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001339 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001340 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001341 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001342 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001343 }
1344 }
1345
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001346 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001347 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001348 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001349 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001350 }
1351 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001352
1353 /**
1354 * Monitor the daemons we started, moving to disconnected state if the
1355 * underlying services fail.
1356 */
1357 private void monitorDaemons() {
1358 if (!mNetworkInfo.isConnected()) {
1359 return;
1360 }
1361
1362 try {
1363 while (true) {
1364 Thread.sleep(2000);
1365 for (int i = 0; i < mDaemons.length; i++) {
1366 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1367 return;
1368 }
1369 }
1370 }
1371 } catch (InterruptedException e) {
1372 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1373 } finally {
1374 for (String daemon : mDaemons) {
1375 SystemService.stop(daemon);
1376 }
1377
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001378 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001379 }
1380 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001381 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001382}