blob: 4100ae91eabfb5fe94dc9179dff5fee9d784e371 [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;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070022import static android.system.OsConstants.AF_INET;
23import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070024
Chad Brubaker4ca19e82013-06-14 11:16:51 -070025import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070026import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070027import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070028import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070029import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070030import android.content.Context;
31import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070032import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070033import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040036import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070038import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070039import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070040import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070041import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090042import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070043import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070044import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070045import android.net.LocalSocket;
46import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040047import android.net.NetworkAgent;
48import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070049import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040050import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070051import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070052import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040053import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070054import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080055import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070056import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040058import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070059import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070060import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070061import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070062import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070063import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070064import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070065import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070066import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070067import android.security.Credentials;
68import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070069import android.util.Log;
70
Chad Brubakerc2865192013-07-10 14:46:23 -070071import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070072import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070073import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070074import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070075import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076
Jeff Davidson05542602014-08-11 14:07:27 -070077import libcore.io.IoUtils;
78
Chia-chi Yeh97a61562011-07-14 15:05:05 -070079import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070080import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070082import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070083import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070084import java.net.Inet6Address;
85import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070086import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040087import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070088import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040089import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040090import java.util.SortedSet;
91import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070092import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070093
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070094/**
95 * @hide
96 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040097public class Vpn {
98 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -070099 private static final String TAG = "Vpn";
100 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400101
Jeff Sharkey899223b2012-08-04 15:24:58 -0700102 // TODO: create separate trackers for each unique VPN to support
103 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700104
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400105 private Context mContext;
106 private NetworkInfo mNetworkInfo;
107 private String mPackage;
108 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700109 private String mInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700110 private boolean mAllowIPv4;
111 private boolean mAllowIPv6;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700112 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700113 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700114 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700115 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700116 private final IConnectivityManager mConnService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700118 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400119 private NetworkAgent mNetworkAgent;
120 private final Looper mLooper;
121 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700122
123 /* list of users using this VPN. */
124 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400125 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700126 private BroadcastReceiver mUserIntentReceiver = null;
127
Paul Jensen0784eea2014-08-19 16:00:24 -0400128 // Handle of user initiating VPN.
129 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400132 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700135 mConnService = connService;
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) {
218 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700219 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Jeff Davidson05542602014-08-11 14:07:27 -0700220 // The package doesn't match. If this VPN was not previously authorized, return false
221 // to force user authorization. Otherwise, revoke the VPN anyway.
222 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
223 long token = Binder.clearCallingIdentity();
224 try {
225 // This looks bizarre, but it is what ConfirmDialog in VpnDialogs is doing when
226 // the user clicks through to allow the VPN to consent. So we are emulating the
227 // action of the dialog without actually showing it.
228 prepare(null, oldPackage);
229 } finally {
230 Binder.restoreCallingIdentity(token);
231 }
232 return true;
233 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700234 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700235 }
236
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700237 // Return true if we do not need to revoke.
238 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700239 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700240 return true;
241 }
242
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700243 // Check if the caller is authorized.
244 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700245
Jeff Davidson05542602014-08-11 14:07:27 -0700246 // Reset the interface.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700247 if (mInterface != null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700248 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400249 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700250 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700251 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700252 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700253 }
254
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700255 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700256 if (mConnection != null) {
257 try {
258 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
259 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
260 } catch (Exception e) {
261 // ignore
262 }
263 mContext.unbindService(mConnection);
264 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700265 } else if (mLegacyVpnRunner != null) {
266 mLegacyVpnRunner.exit();
267 mLegacyVpnRunner = null;
268 }
269
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400270 long token = Binder.clearCallingIdentity();
271 try {
272 mNetd.denyProtect(mOwnerUID);
273 } catch (Exception e) {
274 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
275 } finally {
276 Binder.restoreCallingIdentity(token);
277 }
278
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700279 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
280 mPackage = newPackage;
Paul Jensen0784eea2014-08-19 16:00:24 -0400281 mOwnerUID = getAppUid(newPackage, mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400282 token = Binder.clearCallingIdentity();
283 try {
284 mNetd.allowProtect(mOwnerUID);
285 } catch (Exception e) {
286 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
287 } finally {
288 Binder.restoreCallingIdentity(token);
289 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700290 mConfig = null;
Jeff Davidson05542602014-08-11 14:07:27 -0700291
Jeff Sharkey899223b2012-08-04 15:24:58 -0700292 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700293 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700294 }
295
Jeff Davidson05542602014-08-11 14:07:27 -0700296 /**
297 * Set whether the current package has the ability to launch VPNs without user intervention.
298 */
299 public void setPackageAuthorization(boolean authorized) {
300 // Check if the caller is authorized.
301 enforceControlPermission();
302
303 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
304 return;
305 }
306
307 long token = Binder.clearCallingIdentity();
308 try {
309 AppOpsManager appOps =
310 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
311 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
312 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
313 } catch (Exception e) {
314 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
315 } finally {
316 Binder.restoreCallingIdentity(token);
317 }
318 }
319
320 private boolean isVpnUserPreConsented(String packageName) {
321 AppOpsManager appOps =
322 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
323
324 // Verify that the caller matches the given package and has permission to activate VPNs.
325 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
326 packageName) == AppOpsManager.MODE_ALLOWED;
327 }
328
Paul Jensen0784eea2014-08-19 16:00:24 -0400329 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700330 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400331 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700332 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400333 PackageManager pm = mContext.getPackageManager();
334 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700335 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400336 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400337 } catch (NameNotFoundException e) {
338 result = -1;
339 }
340 return result;
341 }
342
343 public NetworkInfo getNetworkInfo() {
344 return mNetworkInfo;
345 }
346
347 private void agentConnect() {
348 LinkProperties lp = new LinkProperties();
349 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700350
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400351 boolean hasDefaultRoute = false;
352 for (RouteInfo route : mConfig.routes) {
353 lp.addRoute(route);
354 if (route.isDefaultRoute()) hasDefaultRoute = true;
355 }
356 if (hasDefaultRoute) {
357 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
358 } else {
359 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
360 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700361
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400362 if (mConfig.dnsServers != null) {
363 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700364 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
365 lp.addDnsServer(address);
366 if (address instanceof Inet4Address) {
367 mAllowIPv4 = true;
368 } else {
369 mAllowIPv6 = true;
370 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400371 }
372 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700373
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400374 // Concatenate search domains into a string.
375 StringBuilder buffer = new StringBuilder();
376 if (mConfig.searchDomains != null) {
377 for (String domain : mConfig.searchDomains) {
378 buffer.append(domain).append(' ');
379 }
380 }
381 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700382
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400383 mNetworkInfo.setIsAvailable(true);
384 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700385
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700386 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700387 networkMisc.allowBypass = mConfig.allowBypass;
388
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400389 long token = Binder.clearCallingIdentity();
390 try {
391 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700392 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700393 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400394 public void unwanted() {
395 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700396 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400397 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700398 } finally {
399 Binder.restoreCallingIdentity(token);
400 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700401
402 if (!mAllowIPv4) {
403 mNetworkAgent.blockAddressFamily(AF_INET);
404 }
405 if (!mAllowIPv6) {
406 mNetworkAgent.blockAddressFamily(AF_INET6);
407 }
408
Paul Jensen0784eea2014-08-19 16:00:24 -0400409 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400410 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400411 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400412 token = Binder.clearCallingIdentity();
413 List<UserInfo> users;
414 try {
415 users = UserManager.get(mContext).getUsers();
416 } finally {
417 Binder.restoreCallingIdentity(token);
418 }
419 for (UserInfo user : users) {
420 if (user.isRestricted()) {
421 addVpnUserLocked(user.id);
422 }
423 }
424 }
425 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
426 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700427
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400428 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
429 networkInfo.setIsAvailable(false);
430 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
431 if (networkAgent != null) {
432 networkAgent.sendNetworkInfo(networkInfo);
433 }
434 }
435
436 private void agentDisconnect(NetworkAgent networkAgent) {
437 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
438 agentDisconnect(networkInfo, networkAgent);
439 }
440
441 private void agentDisconnect() {
442 if (mNetworkInfo.isConnected()) {
443 agentDisconnect(mNetworkInfo, mNetworkAgent);
444 mNetworkAgent = null;
445 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700446 }
447
448 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700449 * Establish a VPN network and return the file descriptor of the VPN
450 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700451 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700452 *
453 * @param config The parameters to configure the network.
454 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700455 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700456 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700457 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700458 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400459 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700460 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700461 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700462 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700463 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
464 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700465 long token = Binder.clearCallingIdentity();
466 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700467 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400468 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400469 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700470 throw new SecurityException("Restricted users cannot establish VPNs");
471 }
472
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700473 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400474 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700475 if (info == null) {
476 throw new SecurityException("Cannot find " + config.user);
477 }
478 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
479 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
480 }
481 } catch (RemoteException e) {
482 throw new SecurityException("Cannot find " + config.user);
483 } finally {
484 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700485 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700486
Chad Brubaker850eb672014-03-21 21:02:47 +0000487 // Save the old config in case we need to go back.
488 VpnConfig oldConfig = mConfig;
489 String oldInterface = mInterface;
490 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400491 NetworkAgent oldNetworkAgent = mNetworkAgent;
492 mNetworkAgent = null;
493 List<UidRange> oldUsers = mVpnUsers;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700494 boolean oldAllowIPv4 = mAllowIPv4;
495 boolean oldAllowIPv6 = mAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000496
Chia-chi Yehe9107902011-07-02 01:48:50 -0700497 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700498 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700499 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700500 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700501 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700502
Chad Brubakerc2865192013-07-10 14:46:23 -0700503 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700504 StringBuilder builder = new StringBuilder();
505 for (LinkAddress address : config.addresses) {
506 builder.append(" " + address);
507 }
508 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700509 throw new IllegalArgumentException("At least one address must be specified");
510 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700511 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700512 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400513 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700514 throw new IllegalStateException("Cannot bind " + config.user);
515 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000516
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700517 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700518 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700519
520 // Fill more values.
521 config.user = mPackage;
522 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700523 config.startTime = SystemClock.elapsedRealtime();
524 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000525
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700526 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400527 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700528 mAllowIPv4 = mConfig.allowIPv4;
529 mAllowIPv6 = mConfig.allowIPv6;
530
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400531 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000532
533 if (oldConnection != null) {
534 mContext.unbindService(oldConnection);
535 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400536 // Remove the old tun's user forwarding rules
537 // The new tun's user rules have already been added so they will take over
538 // as rules are deleted. This prevents data leakage as the rules are moved over.
539 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000540 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000541 jniReset(oldInterface);
542 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700543
544 try {
545 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
546 } catch (IOException e) {
547 throw new IllegalStateException(
548 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
549 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000550 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000551 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400552 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000553 // restore old state
554 mConfig = oldConfig;
555 mConnection = oldConnection;
556 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400557 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000558 mInterface = oldInterface;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700559 mAllowIPv4 = oldAllowIPv4;
560 mAllowIPv6 = oldAllowIPv6;
Chad Brubaker850eb672014-03-21 21:02:47 +0000561 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700562 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700564 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700565 }
566
Chad Brubakerc2865192013-07-10 14:46:23 -0700567 private boolean isRunningLocked() {
568 return mVpnUsers != null;
569 }
570
Paul Jensen0784eea2014-08-19 16:00:24 -0400571 // Note: Return type guarantees results are deduped and sorted, which callers require.
572 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
573 SortedSet<Integer> uids = new TreeSet<Integer>();
574 for (String app : packageNames) {
575 int uid = getAppUid(app, userHandle);
576 if (uid != -1) uids.add(uid);
577 }
578 return uids;
579 }
580
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400581 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400582 private void addVpnUserLocked(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700583 if (!isRunningLocked()) {
584 throw new IllegalStateException("VPN is not active");
585 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700586
Paul Jensen0784eea2014-08-19 16:00:24 -0400587 if (mConfig.allowedApplications != null) {
588 // Add ranges covering all UIDs for allowedApplications.
589 int start = -1, stop = -1;
590 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
591 if (start == -1) {
592 start = uid;
593 } else if (uid != stop + 1) {
594 mVpnUsers.add(new UidRange(start, stop));
595 start = uid;
596 }
597 stop = uid;
598 }
599 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
600 } else if (mConfig.disallowedApplications != null) {
601 // Add all ranges for user skipping UIDs for disallowedApplications.
602 final UidRange userRange = UidRange.createForUser(userHandle);
603 int start = userRange.start;
604 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
605 if (uid == start) {
606 start++;
607 } else {
608 mVpnUsers.add(new UidRange(start, uid - 1));
609 start = uid + 1;
610 }
611 }
612 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
613 } else {
614 // Add all UIDs for the user.
615 mVpnUsers.add(UidRange.createForUser(userHandle));
616 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700617
618 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700619 }
620
Paul Jensen0784eea2014-08-19 16:00:24 -0400621 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
622 // apply to userHandle.
623 private List<UidRange> uidRangesForUser(int userHandle) {
624 final UidRange userRange = UidRange.createForUser(userHandle);
625 final List<UidRange> ranges = new ArrayList<UidRange>();
626 for (UidRange range : mVpnUsers) {
627 if (range.start >= userRange.start && range.stop <= userRange.stop) {
628 ranges.add(range);
629 }
630 }
631 return ranges;
632 }
633
634 private void removeVpnUserLocked(int userHandle) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700635 if (!isRunningLocked()) {
636 throw new IllegalStateException("VPN is not active");
637 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400638 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700639 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400640 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700641 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400642 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700643 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700644 }
645
Paul Jensen0784eea2014-08-19 16:00:24 -0400646 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700647 // If the user is restricted tie them to the owner's VPN
648 synchronized(Vpn.this) {
649 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400650 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700651 if (user.isRestricted()) {
652 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400653 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400654 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400655 final List<UidRange> ranges = uidRangesForUser(userHandle);
656 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400657 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700658 } catch (Exception e) {
659 Log.wtf(TAG, "Failed to add restricted user to owner", e);
660 }
661 }
662 }
663 }
664
Paul Jensen0784eea2014-08-19 16:00:24 -0400665 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700666 // clean up if restricted
667 synchronized(Vpn.this) {
668 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400669 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700670 if (user.isRestricted()) {
671 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400672 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700673 } catch (Exception e) {
674 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
675 }
676 }
677 }
678 }
679
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700680 /**
681 * Return the configuration of the currently running VPN.
682 */
683 public VpnConfig getVpnConfig() {
684 enforceControlPermission();
685 return mConfig;
686 }
687
Jeff Sharkey899223b2012-08-04 15:24:58 -0700688 @Deprecated
689 public synchronized void interfaceStatusChanged(String iface, boolean up) {
690 try {
691 mObserver.interfaceStatusChanged(iface, up);
692 } catch (RemoteException e) {
693 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700694 }
695 }
696
Jeff Sharkey899223b2012-08-04 15:24:58 -0700697 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
698 @Override
699 public void interfaceStatusChanged(String interfaze, boolean up) {
700 synchronized (Vpn.this) {
701 if (!up && mLegacyVpnRunner != null) {
702 mLegacyVpnRunner.check(interfaze);
703 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700704 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700705 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700706
Jeff Sharkey899223b2012-08-04 15:24:58 -0700707 @Override
708 public void interfaceRemoved(String interfaze) {
709 synchronized (Vpn.this) {
710 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700711 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400712 mVpnUsers = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700713 mInterface = null;
714 if (mConnection != null) {
715 mContext.unbindService(mConnection);
716 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400717 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700718 } else if (mLegacyVpnRunner != null) {
719 mLegacyVpnRunner.exit();
720 mLegacyVpnRunner = null;
721 }
722 }
723 }
724 }
725 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700726
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700727 private void enforceControlPermission() {
728 // System user is allowed to control VPN.
729 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
730 return;
731 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700732 int appId = UserHandle.getAppId(Binder.getCallingUid());
733 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700734 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700735 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700736 PackageManager pm = mContext.getPackageManager();
737 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700738 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700739 return;
740 }
Jason Monke47df842014-07-30 16:41:52 -0400741 // SystemUI dialogs are also allowed to control VPN.
742 ApplicationInfo sysUiApp = pm.getApplicationInfo("com.android.systemui", 0);
743 if (((sysUiApp.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == sysUiApp.uid)) {
744 return;
745 }
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700746 } catch (Exception e) {
747 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700748 } finally {
749 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700750 }
751
752 throw new SecurityException("Unauthorized Caller");
753 }
754
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700755 private class Connection implements ServiceConnection {
756 private IBinder mService;
757
758 @Override
759 public void onServiceConnected(ComponentName name, IBinder service) {
760 mService = service;
761 }
762
763 @Override
764 public void onServiceDisconnected(ComponentName name) {
765 mService = null;
766 }
767 }
768
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700769 private void prepareStatusIntent() {
770 final long token = Binder.clearCallingIdentity();
771 try {
772 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
773 } finally {
774 Binder.restoreCallingIdentity(token);
775 }
776 }
777
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700778 public synchronized boolean addAddress(String address, int prefixLength) {
779 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
780 return false;
781 }
782 boolean success = jniAddAddress(mInterface, address, prefixLength);
783 if (success && (!mAllowIPv4 || !mAllowIPv6)) {
784 try {
785 InetAddress inetAddress = InetAddress.parseNumericAddress(address);
786 if ((inetAddress instanceof Inet4Address) && !mAllowIPv4) {
787 mAllowIPv4 = true;
788 mNetworkAgent.unblockAddressFamily(AF_INET);
789 } else if ((inetAddress instanceof Inet6Address) && !mAllowIPv6) {
790 mAllowIPv6 = true;
791 mNetworkAgent.unblockAddressFamily(AF_INET6);
792 }
793 } catch (IllegalArgumentException e) {
794 // ignore
795 }
796 }
797 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
798 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
799 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
800 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
801 // TODO: Maybe fix this.
802 return success;
803 }
804
805 public synchronized boolean removeAddress(String address, int prefixLength) {
806 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
807 return false;
808 }
809 boolean success = jniDelAddress(mInterface, address, prefixLength);
810 // Ideally, we'd call mNetworkAgent.sendLinkProperties() here to notify ConnectivityService
811 // that the LinkAddress has changed. But we don't do so for two reasons: (1) We don't set
812 // LinkAddresses on the LinkProperties we establish in the first place (see agentConnect())
813 // and (2) CS doesn't do anything with LinkAddresses anyway (see updateLinkProperties()).
814 // TODO: Maybe fix this.
815 return success;
816 }
817
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700818 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700819 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700820 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700821 private native void jniReset(String interfaze);
822 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700823 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
824 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700825
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900826 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
827 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700828 // Currently legacy VPN only works on IPv4.
829 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900830 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700831 }
832 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700833
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900834 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700835 }
836
837 /**
838 * Start legacy VPN, controlling native daemons as needed. Creates a
839 * secondary thread to perform connection work, returning quickly.
840 */
841 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800842 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800843 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700844 throw new IllegalStateException("KeyStore isn't unlocked");
845 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400846 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400847 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400848 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
849 throw new SecurityException("Restricted users cannot establish VPNs");
850 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700851
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900852 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
853 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
854 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700855
856 // Load certificates.
857 String privateKey = "";
858 String userCert = "";
859 String caCert = "";
860 String serverCert = "";
861 if (!profile.ipsecUserCert.isEmpty()) {
862 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
863 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700864 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700865 }
866 if (!profile.ipsecCaCert.isEmpty()) {
867 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700868 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700869 }
870 if (!profile.ipsecServerCert.isEmpty()) {
871 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700872 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700873 }
874 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
875 throw new IllegalStateException("Cannot load credentials");
876 }
877
878 // Prepare arguments for racoon.
879 String[] racoon = null;
880 switch (profile.type) {
881 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
882 racoon = new String[] {
883 iface, profile.server, "udppsk", profile.ipsecIdentifier,
884 profile.ipsecSecret, "1701",
885 };
886 break;
887 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
888 racoon = new String[] {
889 iface, profile.server, "udprsa", privateKey, userCert,
890 caCert, serverCert, "1701",
891 };
892 break;
893 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
894 racoon = new String[] {
895 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
896 profile.ipsecSecret, profile.username, profile.password, "", gateway,
897 };
898 break;
899 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
900 racoon = new String[] {
901 iface, profile.server, "xauthrsa", privateKey, userCert,
902 caCert, serverCert, profile.username, profile.password, "", gateway,
903 };
904 break;
905 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
906 racoon = new String[] {
907 iface, profile.server, "hybridrsa",
908 caCert, serverCert, profile.username, profile.password, "", gateway,
909 };
910 break;
911 }
912
913 // Prepare arguments for mtpd.
914 String[] mtpd = null;
915 switch (profile.type) {
916 case VpnProfile.TYPE_PPTP:
917 mtpd = new String[] {
918 iface, "pptp", profile.server, "1723",
919 "name", profile.username, "password", profile.password,
920 "linkname", "vpn", "refuse-eap", "nodefaultroute",
921 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
922 (profile.mppe ? "+mppe" : "nomppe"),
923 };
924 break;
925 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
926 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
927 mtpd = new String[] {
928 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
929 "name", profile.username, "password", profile.password,
930 "linkname", "vpn", "refuse-eap", "nodefaultroute",
931 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
932 };
933 break;
934 }
935
936 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700937 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700938 config.user = profile.key;
939 config.interfaze = iface;
940 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700941
942 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700943 if (!profile.dnsServers.isEmpty()) {
944 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
945 }
946 if (!profile.searchDomains.isEmpty()) {
947 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
948 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700949 startLegacyVpn(config, racoon, mtpd);
950 }
951
952 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
953 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700954
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700955 // Prepare for the new request. This also checks the caller.
956 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700957 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700958
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700959 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700960 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
961 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700962 }
963
Jeff Sharkey899223b2012-08-04 15:24:58 -0700964 public synchronized void stopLegacyVpn() {
965 if (mLegacyVpnRunner != null) {
966 mLegacyVpnRunner.exit();
967 mLegacyVpnRunner = null;
968
969 synchronized (LegacyVpnRunner.TAG) {
970 // wait for old thread to completely finish before spinning up
971 // new instance, otherwise state updates can be out of order.
972 }
973 }
974 }
975
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700976 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700977 * Return the information of the current ongoing legacy VPN.
978 */
979 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700980 // Check if the caller is authorized.
981 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700982 if (mLegacyVpnRunner == null) return null;
983
984 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700985 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700986 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700987 if (mNetworkInfo.isConnected()) {
988 info.intent = mStatusIntent;
989 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700990 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700991 }
992
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700993 public VpnConfig getLegacyVpnConfig() {
994 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700995 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700996 } else {
997 return null;
998 }
999 }
1000
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001001 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001002 * Bringing up a VPN connection takes time, and that is all this thread
1003 * does. Here we have plenty of time. The only thing we need to take
1004 * care of is responding to interruptions as soon as possible. Otherwise
1005 * requests will be piled up. This can be done in a Handler as a state
1006 * machine, but it is much easier to read in the current form.
1007 */
1008 private class LegacyVpnRunner extends Thread {
1009 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001010
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001011 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001012 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001013 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001014 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001015 private final AtomicInteger mOuterConnection =
1016 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001017
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001018 private long mTimer = -1;
1019
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001020 /**
1021 * Watch for the outer connection (passing in the constructor) going away.
1022 */
1023 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1024 @Override
1025 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001026 if (!mEnableTeardown) return;
1027
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001028 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1029 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1030 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1031 NetworkInfo info = (NetworkInfo)intent.getExtra(
1032 ConnectivityManager.EXTRA_NETWORK_INFO);
1033 if (info != null && !info.isConnectedOrConnecting()) {
1034 try {
1035 mObserver.interfaceStatusChanged(mOuterInterface, false);
1036 } catch (RemoteException e) {}
1037 }
1038 }
1039 }
1040 }
1041 };
1042
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001043 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001044 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001045 mConfig = config;
1046 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001047 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001048 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001049 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001050
1051 // This is the interface which VPN is running on,
1052 // mConfig.interfaze will change to point to OUR
1053 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001054 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001055 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001056 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001057 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001058
1059 try {
1060 mOuterConnection.set(
1061 mConnService.findConnectionTypeForIface(mOuterInterface));
1062 } catch (Exception e) {
1063 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1064 }
1065
1066 IntentFilter filter = new IntentFilter();
1067 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1068 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001069 }
1070
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001071 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001072 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001073 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1074 exit();
1075 }
1076 }
1077
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001078 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001079 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001080 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001081 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001082 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001083 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001084 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001085 try {
1086 mContext.unregisterReceiver(mBroadcastReceiver);
1087 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001088 }
1089
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001090 @Override
1091 public void run() {
1092 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001093 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001094 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001095 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001096 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001097 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001098 }
1099 }
1100
1101 private void checkpoint(boolean yield) throws InterruptedException {
1102 long now = SystemClock.elapsedRealtime();
1103 if (mTimer == -1) {
1104 mTimer = now;
1105 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001106 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001107 Thread.sleep(yield ? 200 : 1);
1108 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001109 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001110 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001111 }
1112 }
1113
1114 private void execute() {
1115 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001116 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001117 try {
1118 // Initialize the timer.
1119 checkpoint(false);
1120
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001121 // Wait for the daemons to stop.
1122 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001123 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001124 checkpoint(true);
1125 }
1126 }
1127
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001128 // Clear the previous state.
1129 File state = new File("/data/misc/vpn/state");
1130 state.delete();
1131 if (state.exists()) {
1132 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001133 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001134 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001135 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001136
Chia-chi Yehe9107902011-07-02 01:48:50 -07001137 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001138 boolean restart = false;
1139 for (String[] arguments : mArguments) {
1140 restart = restart || (arguments != null);
1141 }
1142 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001143 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001144 return;
1145 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001146 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001147
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001148 // Start the daemon with arguments.
1149 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001150 String[] arguments = mArguments[i];
1151 if (arguments == null) {
1152 continue;
1153 }
1154
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001155 // Start the daemon.
1156 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001157 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001158
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001159 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001160 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001161 checkpoint(true);
1162 }
1163
1164 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001165 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001166 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001167 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001168
1169 // Wait for the socket to connect.
1170 while (true) {
1171 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001172 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001173 break;
1174 } catch (Exception e) {
1175 // ignore
1176 }
1177 checkpoint(true);
1178 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001179 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001180
1181 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001182 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001184 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001185 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001186 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001187 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001188 out.write(bytes.length >> 8);
1189 out.write(bytes.length);
1190 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001191 checkpoint(false);
1192 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001193 out.write(0xFF);
1194 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001195 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001196
1197 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001198 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001199 while (true) {
1200 try {
1201 if (in.read() == -1) {
1202 break;
1203 }
1204 } catch (Exception e) {
1205 // ignore
1206 }
1207 checkpoint(true);
1208 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001209 }
1210
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001211 // Wait for the daemons to create the new state.
1212 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001213 // Check if a running daemon is dead.
1214 for (int i = 0; i < mDaemons.length; ++i) {
1215 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001216 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001217 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001218 }
1219 }
1220 checkpoint(true);
1221 }
1222
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001223 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001224 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001225 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001226 throw new IllegalStateException("Cannot parse the state");
1227 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001228
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001229 // Set the interface and the addresses in the config.
1230 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001231
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001232 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001233 // Set the routes if they are not set in the config.
1234 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001235 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001236 }
1237
1238 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001239 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001240 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001241 if (!dnsServers.isEmpty()) {
1242 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1243 }
1244 }
1245
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001246 // Set the search domains if they are not set in the config.
1247 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1248 String searchDomains = parameters[4].trim();
1249 if (!searchDomains.isEmpty()) {
1250 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1251 }
1252 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001253
Lorenzo Colitti50262792014-09-19 01:53:35 +09001254 // Add a throw route for the VPN server endpoint, if one was specified.
1255 String endpoint = parameters[5];
1256 if (!endpoint.isEmpty()) {
1257 try {
1258 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1259 if (addr instanceof Inet4Address) {
1260 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1261 } else if (addr instanceof Inet6Address) {
1262 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1263 } else {
1264 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1265 }
1266 } catch (IllegalArgumentException e) {
1267 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1268 }
1269 }
1270
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001271 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001272 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001273 // Set the start time
1274 mConfig.startTime = SystemClock.elapsedRealtime();
1275
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001276 // Check if the thread is interrupted while we are waiting.
1277 checkpoint(false);
1278
Chia-chi Yehe9107902011-07-02 01:48:50 -07001279 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001280 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001281 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001282 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001283
1284 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001285 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001286 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001287 mAllowIPv4 = mConfig.allowIPv4;
1288 mAllowIPv6 = mConfig.allowIPv6;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001289
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001290 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001291
1292 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001293 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001294 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001295 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001296 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001297 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001298 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001299 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001300 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001301 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001302 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001303 }
1304 }
1305
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001306 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001307 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001308 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001309 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001310 }
1311 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001312
1313 /**
1314 * Monitor the daemons we started, moving to disconnected state if the
1315 * underlying services fail.
1316 */
1317 private void monitorDaemons() {
1318 if (!mNetworkInfo.isConnected()) {
1319 return;
1320 }
1321
1322 try {
1323 while (true) {
1324 Thread.sleep(2000);
1325 for (int i = 0; i < mDaemons.length; i++) {
1326 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1327 return;
1328 }
1329 }
1330 }
1331 } catch (InterruptedException e) {
1332 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1333 } finally {
1334 for (String daemon : mDaemons) {
1335 SystemService.stop(daemon);
1336 }
1337
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001338 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001339 }
1340 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001341 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001342}