blob: e1ec8a636e725c36c2c69054df6c283bb2423287 [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen31a94f42015-02-13 14:18:39 -050020import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti50262792014-09-19 01:53:35 +090021import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090022import static android.net.RouteInfo.RTN_UNREACHABLE;
Paul Jensen31a94f42015-02-13 14:18:39 -050023import static android.os.UserHandle.PER_USER_RANGE;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070024import static android.system.OsConstants.AF_INET;
25import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070026
Jeff Davidsonbc19c182014-11-11 13:20:01 -080027import android.Manifest;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070028import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070029import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070030import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070031import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070032import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.Context;
34import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070035import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040039import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070040import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070041import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070042import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070043import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070044import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090045import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070046import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070047import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070048import android.net.LocalSocket;
49import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080050import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040051import android.net.NetworkAgent;
52import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070053import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040054import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070055import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070056import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040057import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070058import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080059import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070060import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070061import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040062import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070063import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070065import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070066import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070067import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070068import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070069import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070070import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070071import android.security.Credentials;
72import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040073import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import android.util.Log;
75
Chad Brubakerc2865192013-07-10 14:46:23 -070076import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070077import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070078import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080079import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070081import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082
Jeff Davidson05542602014-08-11 14:07:27 -070083import libcore.io.IoUtils;
84
Chia-chi Yeh97a61562011-07-14 15:05:05 -070085import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070086import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070087import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070088import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070089import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070090import java.net.Inet6Address;
91import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070092import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040093import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070094import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040095import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040096import java.util.SortedSet;
97import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070098import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070099
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700100/**
101 * @hide
102 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103public class Vpn {
104 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 private static final String TAG = "Vpn";
106 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107
Jeff Sharkey899223b2012-08-04 15:24:58 -0700108 // TODO: create separate trackers for each unique VPN to support
109 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700110
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400111 private Context mContext;
112 private NetworkInfo mNetworkInfo;
113 private String mPackage;
114 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700115 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700116 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700117 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700118 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700119 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400120 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400122 private NetworkAgent mNetworkAgent;
123 private final Looper mLooper;
124 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700125
126 /* list of users using this VPN. */
127 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700129 private BroadcastReceiver mUserIntentReceiver = null;
130
Paul Jensen0784eea2014-08-19 16:00:24 -0400131 // Handle of user initiating VPN.
132 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700133
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400135 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700136 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400138 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400139 mLooper = looper;
140
141 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400142 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700143
144 try {
145 netService.registerObserver(mObserver);
146 } catch (RemoteException e) {
147 Log.wtf(TAG, "Problem registering observer", e);
148 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400149 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700150 // Owner's VPN also needs to handle restricted users
151 mUserIntentReceiver = new BroadcastReceiver() {
152 @Override
153 public void onReceive(Context context, Intent intent) {
154 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400155 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700156 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400157 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700158
159 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400160 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700161 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400162 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700163 }
164 }
165 };
166
167 IntentFilter intentFilter = new IntentFilter();
168 intentFilter.addAction(Intent.ACTION_USER_ADDED);
169 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
170 mContext.registerReceiverAsUser(
171 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
172 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173
174 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
175 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
176 mNetworkCapabilities = new NetworkCapabilities();
177 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
178 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700179 }
180
Jeff Sharkey57666932013-04-30 17:01:57 -0700181 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700182 * Set if this object is responsible for watching for {@link NetworkInfo}
183 * teardown. When {@code false}, teardown is handled externally by someone
184 * else.
185 */
186 public void setEnableTeardown(boolean enableTeardown) {
187 mEnableTeardown = enableTeardown;
188 }
189
Jeff Sharkey899223b2012-08-04 15:24:58 -0700190 /**
191 * Update current state, dispaching event to listeners.
192 */
193 private void updateState(DetailedState detailedState, String reason) {
194 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
195 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400196 if (mNetworkAgent != null) {
197 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
198 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199 }
200
201 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700202 * Prepare for a VPN application. This method is designed to solve
203 * race conditions. It first compares the current prepared package
204 * with {@code oldPackage}. If they are the same, the prepared
205 * package is revoked and replaced with {@code newPackage}. If
206 * {@code oldPackage} is {@code null}, the comparison is omitted.
207 * If {@code newPackage} is the same package or {@code null}, the
208 * revocation is omitted. This method returns {@code true} if the
209 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700210 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700211 * Legacy VPN is handled specially since it is not a real package.
212 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
213 * it can be revoked by itself.
214 *
215 * @param oldPackage The package name of the old VPN application.
216 * @param newPackage The package name of the new VPN application.
217 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700218 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700219 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700220 if (oldPackage != null) {
221 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
222 // The package doesn't match. We return false (to obtain user consent) unless the
223 // user has already consented to that VPN package.
224 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
225 prepareInternal(oldPackage);
226 return true;
227 }
228 return false;
229 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
230 && !isVpnUserPreConsented(oldPackage)) {
231 // Currently prepared VPN is revoked, so unprepare it and return false.
232 prepareInternal(VpnConfig.LEGACY_VPN);
233 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700234 }
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.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700238 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
239 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
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 Davidson11008a72014-11-20 13:12:46 -0800246 prepareInternal(newPackage);
247 return true;
248 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700249
Jeff Davidson11008a72014-11-20 13:12:46 -0800250 /** Prepare the VPN for the given package. Does not perform permission checks. */
251 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400252 long token = Binder.clearCallingIdentity();
253 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800254 // Reset the interface.
255 if (mInterface != null) {
256 mStatusIntent = null;
257 agentDisconnect();
258 jniReset(mInterface);
259 mInterface = null;
260 mVpnUsers = null;
261 }
262
263 // Revoke the connection or stop LegacyVpnRunner.
264 if (mConnection != null) {
265 try {
266 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
267 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
268 } catch (Exception e) {
269 // ignore
270 }
271 mContext.unbindService(mConnection);
272 mConnection = null;
273 } else if (mLegacyVpnRunner != null) {
274 mLegacyVpnRunner.exit();
275 mLegacyVpnRunner = null;
276 }
277
278 try {
279 mNetd.denyProtect(mOwnerUID);
280 } catch (Exception e) {
281 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
282 }
283
284 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
285 mPackage = newPackage;
286 mOwnerUID = getAppUid(newPackage, mUserHandle);
287 try {
288 mNetd.allowProtect(mOwnerUID);
289 } catch (Exception e) {
290 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
291 }
292 mConfig = null;
293
294 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400295 } finally {
296 Binder.restoreCallingIdentity(token);
297 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700298 }
299
Jeff Davidson05542602014-08-11 14:07:27 -0700300 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100301 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700302 */
Robin Lee3b3dd942015-05-12 18:14:58 +0100303 public void setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700304 // Check if the caller is authorized.
305 enforceControlPermission();
306
Robin Lee3b3dd942015-05-12 18:14:58 +0100307 int uid = getAppUid(packageName, mUserHandle);
308 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
309 // Authorization for nonexistent packages (or fake ones) can't be updated.
Jeff Davidson05542602014-08-11 14:07:27 -0700310 return;
311 }
312
313 long token = Binder.clearCallingIdentity();
314 try {
315 AppOpsManager appOps =
316 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100317 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700318 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
319 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100320 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700321 } finally {
322 Binder.restoreCallingIdentity(token);
323 }
324 }
325
326 private boolean isVpnUserPreConsented(String packageName) {
327 AppOpsManager appOps =
328 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
329
330 // Verify that the caller matches the given package and has permission to activate VPNs.
331 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
332 packageName) == AppOpsManager.MODE_ALLOWED;
333 }
334
Paul Jensen0784eea2014-08-19 16:00:24 -0400335 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700336 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400337 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700338 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400339 PackageManager pm = mContext.getPackageManager();
340 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700341 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400342 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400343 } catch (NameNotFoundException e) {
344 result = -1;
345 }
346 return result;
347 }
348
349 public NetworkInfo getNetworkInfo() {
350 return mNetworkInfo;
351 }
352
Paul Jensen31a94f42015-02-13 14:18:39 -0500353 public int getNetId() {
354 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
355 }
356
Lorenzo Colitti60446162014-09-20 00:14:31 +0900357 private LinkProperties makeLinkProperties() {
358 boolean allowIPv4 = mConfig.allowIPv4;
359 boolean allowIPv6 = mConfig.allowIPv6;
360
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400361 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900362
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400363 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700364
Lorenzo Colitti60446162014-09-20 00:14:31 +0900365 if (mConfig.addresses != null) {
366 for (LinkAddress address : mConfig.addresses) {
367 lp.addLinkAddress(address);
368 allowIPv4 |= address.getAddress() instanceof Inet4Address;
369 allowIPv6 |= address.getAddress() instanceof Inet6Address;
370 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400371 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900372
373 if (mConfig.routes != null) {
374 for (RouteInfo route : mConfig.routes) {
375 lp.addRoute(route);
376 InetAddress address = route.getDestination().getAddress();
377 allowIPv4 |= address instanceof Inet4Address;
378 allowIPv6 |= address instanceof Inet6Address;
379 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400380 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700381
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400382 if (mConfig.dnsServers != null) {
383 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700384 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
385 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900386 allowIPv4 |= address instanceof Inet4Address;
387 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400388 }
389 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700390
Lorenzo Colitti60446162014-09-20 00:14:31 +0900391 if (!allowIPv4) {
392 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
393 }
394 if (!allowIPv6) {
395 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
396 }
397
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400398 // Concatenate search domains into a string.
399 StringBuilder buffer = new StringBuilder();
400 if (mConfig.searchDomains != null) {
401 for (String domain : mConfig.searchDomains) {
402 buffer.append(domain).append(' ');
403 }
404 }
405 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700406
Lorenzo Colitti60446162014-09-20 00:14:31 +0900407 // TODO: Stop setting the MTU in jniCreate and set it here.
408
409 return lp;
410 }
411
412 private void agentConnect() {
413 LinkProperties lp = makeLinkProperties();
414
415 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
416 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
417 } else {
418 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
419 }
420
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400421 mNetworkInfo.setIsAvailable(true);
422 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700423
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700424 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700425 networkMisc.allowBypass = mConfig.allowBypass;
426
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400427 long token = Binder.clearCallingIdentity();
428 try {
429 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700430 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700431 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400432 public void unwanted() {
433 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700434 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400435 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700436 } finally {
437 Binder.restoreCallingIdentity(token);
438 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700439
Paul Jensen0784eea2014-08-19 16:00:24 -0400440 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400441 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400442 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400443 token = Binder.clearCallingIdentity();
444 List<UserInfo> users;
445 try {
446 users = UserManager.get(mContext).getUsers();
447 } finally {
448 Binder.restoreCallingIdentity(token);
449 }
450 for (UserInfo user : users) {
451 if (user.isRestricted()) {
452 addVpnUserLocked(user.id);
453 }
454 }
455 }
456 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
457 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700458
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400459 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
460 networkInfo.setIsAvailable(false);
461 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
462 if (networkAgent != null) {
463 networkAgent.sendNetworkInfo(networkInfo);
464 }
465 }
466
467 private void agentDisconnect(NetworkAgent networkAgent) {
468 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
469 agentDisconnect(networkInfo, networkAgent);
470 }
471
472 private void agentDisconnect() {
473 if (mNetworkInfo.isConnected()) {
474 agentDisconnect(mNetworkInfo, mNetworkAgent);
475 mNetworkAgent = null;
476 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700477 }
478
479 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700480 * Establish a VPN network and return the file descriptor of the VPN
481 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700482 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700483 *
484 * @param config The parameters to configure the network.
485 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700486 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700487 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700488 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700489 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400490 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700491 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700492 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700493 // Check to ensure consent hasn't been revoked since we were prepared.
494 if (!isVpnUserPreConsented(mPackage)) {
495 return null;
496 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700497 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700498 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
499 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700500 long token = Binder.clearCallingIdentity();
501 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700502 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400503 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000504 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
505 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700506 throw new SecurityException("Restricted users cannot establish VPNs");
507 }
508
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700509 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400510 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700511 if (info == null) {
512 throw new SecurityException("Cannot find " + config.user);
513 }
514 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
515 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
516 }
517 } catch (RemoteException e) {
518 throw new SecurityException("Cannot find " + config.user);
519 } finally {
520 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700521 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700522
Chad Brubaker850eb672014-03-21 21:02:47 +0000523 // Save the old config in case we need to go back.
524 VpnConfig oldConfig = mConfig;
525 String oldInterface = mInterface;
526 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400527 NetworkAgent oldNetworkAgent = mNetworkAgent;
528 mNetworkAgent = null;
529 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000530
Chia-chi Yehe9107902011-07-02 01:48:50 -0700531 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700532 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700533 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700534 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700535 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700536
Chad Brubakerc2865192013-07-10 14:46:23 -0700537 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700538 StringBuilder builder = new StringBuilder();
539 for (LinkAddress address : config.addresses) {
540 builder.append(" " + address);
541 }
542 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700543 throw new IllegalArgumentException("At least one address must be specified");
544 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700545 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700546 if (!mContext.bindServiceAsUser(intent, connection,
547 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
548 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700549 throw new IllegalStateException("Cannot bind " + config.user);
550 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000551
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700552 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700553 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700554
555 // Fill more values.
556 config.user = mPackage;
557 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700558 config.startTime = SystemClock.elapsedRealtime();
559 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000560
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700561 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400562 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700563
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400564 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000565
566 if (oldConnection != null) {
567 mContext.unbindService(oldConnection);
568 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 // Remove the old tun's user forwarding rules
570 // The new tun's user rules have already been added so they will take over
571 // as rules are deleted. This prevents data leakage as the rules are moved over.
572 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000573 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000574 jniReset(oldInterface);
575 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700576
577 try {
578 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
579 } catch (IOException e) {
580 throw new IllegalStateException(
581 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
582 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000583 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000584 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400585 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000586 // restore old state
587 mConfig = oldConfig;
588 mConnection = oldConnection;
589 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400590 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000591 mInterface = oldInterface;
592 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700593 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000594 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700595 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700596 }
597
Chad Brubakerc2865192013-07-10 14:46:23 -0700598 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800599 return mNetworkAgent != null && mInterface != null;
600 }
601
602 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
603 // that a call to mutate VPN state is admissible.
604 private boolean isCallerEstablishedOwnerLocked() {
605 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700606 }
607
Paul Jensen0784eea2014-08-19 16:00:24 -0400608 // Note: Return type guarantees results are deduped and sorted, which callers require.
609 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
610 SortedSet<Integer> uids = new TreeSet<Integer>();
611 for (String app : packageNames) {
612 int uid = getAppUid(app, userHandle);
613 if (uid != -1) uids.add(uid);
614 }
615 return uids;
616 }
617
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400618 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400619 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800620 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700621 throw new IllegalStateException("VPN is not active");
622 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700623
Paul Jensen0784eea2014-08-19 16:00:24 -0400624 if (mConfig.allowedApplications != null) {
625 // Add ranges covering all UIDs for allowedApplications.
626 int start = -1, stop = -1;
627 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
628 if (start == -1) {
629 start = uid;
630 } else if (uid != stop + 1) {
631 mVpnUsers.add(new UidRange(start, stop));
632 start = uid;
633 }
634 stop = uid;
635 }
636 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
637 } else if (mConfig.disallowedApplications != null) {
638 // Add all ranges for user skipping UIDs for disallowedApplications.
639 final UidRange userRange = UidRange.createForUser(userHandle);
640 int start = userRange.start;
641 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
642 if (uid == start) {
643 start++;
644 } else {
645 mVpnUsers.add(new UidRange(start, uid - 1));
646 start = uid + 1;
647 }
648 }
649 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
650 } else {
651 // Add all UIDs for the user.
652 mVpnUsers.add(UidRange.createForUser(userHandle));
653 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700654
655 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700656 }
657
Paul Jensen0784eea2014-08-19 16:00:24 -0400658 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
659 // apply to userHandle.
660 private List<UidRange> uidRangesForUser(int userHandle) {
661 final UidRange userRange = UidRange.createForUser(userHandle);
662 final List<UidRange> ranges = new ArrayList<UidRange>();
663 for (UidRange range : mVpnUsers) {
664 if (range.start >= userRange.start && range.stop <= userRange.stop) {
665 ranges.add(range);
666 }
667 }
668 return ranges;
669 }
670
671 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800672 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700673 throw new IllegalStateException("VPN is not active");
674 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400675 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700676 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400677 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700678 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400679 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700680 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700681 }
682
Paul Jensen0784eea2014-08-19 16:00:24 -0400683 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700684 // If the user is restricted tie them to the owner's VPN
685 synchronized(Vpn.this) {
686 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400687 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700688 if (user.isRestricted()) {
689 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400690 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400691 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400692 final List<UidRange> ranges = uidRangesForUser(userHandle);
693 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400694 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700695 } catch (Exception e) {
696 Log.wtf(TAG, "Failed to add restricted user to owner", e);
697 }
698 }
699 }
700 }
701
Paul Jensen0784eea2014-08-19 16:00:24 -0400702 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700703 // clean up if restricted
704 synchronized(Vpn.this) {
705 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400706 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700707 if (user.isRestricted()) {
708 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400709 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700710 } catch (Exception e) {
711 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
712 }
713 }
714 }
715 }
716
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700717 /**
718 * Return the configuration of the currently running VPN.
719 */
720 public VpnConfig getVpnConfig() {
721 enforceControlPermission();
722 return mConfig;
723 }
724
Jeff Sharkey899223b2012-08-04 15:24:58 -0700725 @Deprecated
726 public synchronized void interfaceStatusChanged(String iface, boolean up) {
727 try {
728 mObserver.interfaceStatusChanged(iface, up);
729 } catch (RemoteException e) {
730 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700731 }
732 }
733
Jeff Sharkey899223b2012-08-04 15:24:58 -0700734 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
735 @Override
736 public void interfaceStatusChanged(String interfaze, boolean up) {
737 synchronized (Vpn.this) {
738 if (!up && mLegacyVpnRunner != null) {
739 mLegacyVpnRunner.check(interfaze);
740 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700741 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700742 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700743
Jeff Sharkey899223b2012-08-04 15:24:58 -0700744 @Override
745 public void interfaceRemoved(String interfaze) {
746 synchronized (Vpn.this) {
747 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700748 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400749 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500750 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700751 mInterface = null;
752 if (mConnection != null) {
753 mContext.unbindService(mConnection);
754 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400755 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700756 } else if (mLegacyVpnRunner != null) {
757 mLegacyVpnRunner.exit();
758 mLegacyVpnRunner = null;
759 }
760 }
761 }
762 }
763 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700764
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700765 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800766 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700767 }
768
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700769 private class Connection implements ServiceConnection {
770 private IBinder mService;
771
772 @Override
773 public void onServiceConnected(ComponentName name, IBinder service) {
774 mService = service;
775 }
776
777 @Override
778 public void onServiceDisconnected(ComponentName name) {
779 mService = null;
780 }
781 }
782
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700783 private void prepareStatusIntent() {
784 final long token = Binder.clearCallingIdentity();
785 try {
786 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
787 } finally {
788 Binder.restoreCallingIdentity(token);
789 }
790 }
791
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700792 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800793 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700794 return false;
795 }
796 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800797 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700798 return success;
799 }
800
801 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800802 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700803 return false;
804 }
805 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800806 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700807 return success;
808 }
809
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800810 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
811 if (!isCallerEstablishedOwnerLocked()) {
812 return false;
813 }
814 if (networks == null) {
815 mConfig.underlyingNetworks = null;
816 } else {
817 mConfig.underlyingNetworks = new Network[networks.length];
818 for (int i = 0; i < networks.length; ++i) {
819 if (networks[i] == null) {
820 mConfig.underlyingNetworks[i] = null;
821 } else {
822 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
823 }
824 }
825 }
826 return true;
827 }
828
829 public synchronized Network[] getUnderlyingNetworks() {
830 if (!isRunningLocked()) {
831 return null;
832 }
833 return mConfig.underlyingNetworks;
834 }
835
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800836 /**
837 * This method should only be called by ConnectivityService. Because it doesn't
838 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
839 */
840 public synchronized VpnInfo getVpnInfo() {
841 if (!isRunningLocked()) {
842 return null;
843 }
844
845 VpnInfo info = new VpnInfo();
846 info.ownerUid = mOwnerUID;
847 info.vpnIface = mInterface;
848 return info;
849 }
850
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800851 public synchronized boolean appliesToUid(int uid) {
852 if (!isRunningLocked()) {
853 return false;
854 }
855 for (UidRange uidRange : mVpnUsers) {
856 if (uidRange.start <= uid && uid <= uidRange.stop) {
857 return true;
858 }
859 }
860 return false;
861 }
862
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700863 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700864 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700865 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700866 private native void jniReset(String interfaze);
867 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700868 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
869 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700870
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900871 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
872 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700873 // Currently legacy VPN only works on IPv4.
874 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900875 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700876 }
877 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700878
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900879 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700880 }
881
882 /**
883 * Start legacy VPN, controlling native daemons as needed. Creates a
884 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800885 *
886 * Should only be called to respond to Binder requests as this enforces caller permission. Use
887 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
888 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700889 */
890 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800891 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800892 long token = Binder.clearCallingIdentity();
893 try {
894 startLegacyVpnPrivileged(profile, keyStore, egress);
895 } finally {
896 Binder.restoreCallingIdentity(token);
897 }
898 }
899
900 /**
901 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
902 * permissions under the assumption that the caller is the system.
903 *
904 * Callers are responsible for checking permissions if needed.
905 */
906 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
907 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800908 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700909 throw new IllegalStateException("KeyStore isn't unlocked");
910 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400911 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400912 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000913 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
914 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400915 throw new SecurityException("Restricted users cannot establish VPNs");
916 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700917
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900918 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
919 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
920 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700921
922 // Load certificates.
923 String privateKey = "";
924 String userCert = "";
925 String caCert = "";
926 String serverCert = "";
927 if (!profile.ipsecUserCert.isEmpty()) {
928 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
929 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700930 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700931 }
932 if (!profile.ipsecCaCert.isEmpty()) {
933 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700934 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700935 }
936 if (!profile.ipsecServerCert.isEmpty()) {
937 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700938 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700939 }
940 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
941 throw new IllegalStateException("Cannot load credentials");
942 }
943
944 // Prepare arguments for racoon.
945 String[] racoon = null;
946 switch (profile.type) {
947 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
948 racoon = new String[] {
949 iface, profile.server, "udppsk", profile.ipsecIdentifier,
950 profile.ipsecSecret, "1701",
951 };
952 break;
953 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
954 racoon = new String[] {
955 iface, profile.server, "udprsa", privateKey, userCert,
956 caCert, serverCert, "1701",
957 };
958 break;
959 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
960 racoon = new String[] {
961 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
962 profile.ipsecSecret, profile.username, profile.password, "", gateway,
963 };
964 break;
965 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
966 racoon = new String[] {
967 iface, profile.server, "xauthrsa", privateKey, userCert,
968 caCert, serverCert, profile.username, profile.password, "", gateway,
969 };
970 break;
971 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
972 racoon = new String[] {
973 iface, profile.server, "hybridrsa",
974 caCert, serverCert, profile.username, profile.password, "", gateway,
975 };
976 break;
977 }
978
979 // Prepare arguments for mtpd.
980 String[] mtpd = null;
981 switch (profile.type) {
982 case VpnProfile.TYPE_PPTP:
983 mtpd = new String[] {
984 iface, "pptp", profile.server, "1723",
985 "name", profile.username, "password", profile.password,
986 "linkname", "vpn", "refuse-eap", "nodefaultroute",
987 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
988 (profile.mppe ? "+mppe" : "nomppe"),
989 };
990 break;
991 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
992 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
993 mtpd = new String[] {
994 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
995 "name", profile.username, "password", profile.password,
996 "linkname", "vpn", "refuse-eap", "nodefaultroute",
997 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
998 };
999 break;
1000 }
1001
1002 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001003 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001004 config.user = profile.key;
1005 config.interfaze = iface;
1006 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001007
1008 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001009 if (!profile.dnsServers.isEmpty()) {
1010 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1011 }
1012 if (!profile.searchDomains.isEmpty()) {
1013 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1014 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001015 startLegacyVpn(config, racoon, mtpd);
1016 }
1017
1018 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001019 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001020
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001021 // Prepare for the new request.
1022 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001023 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001024
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001025 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001026 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1027 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001028 }
1029
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001030 /** Stop legacy VPN. Permissions must be checked by callers. */
1031 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001032 if (mLegacyVpnRunner != null) {
1033 mLegacyVpnRunner.exit();
1034 mLegacyVpnRunner = null;
1035
1036 synchronized (LegacyVpnRunner.TAG) {
1037 // wait for old thread to completely finish before spinning up
1038 // new instance, otherwise state updates can be out of order.
1039 }
1040 }
1041 }
1042
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001043 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001044 * Return the information of the current ongoing legacy VPN.
1045 */
1046 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001047 // Check if the caller is authorized.
1048 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001049 return getLegacyVpnInfoPrivileged();
1050 }
1051
1052 /**
1053 * Return the information of the current ongoing legacy VPN.
1054 * Callers are responsible for checking permissions if needed.
1055 */
1056 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001057 if (mLegacyVpnRunner == null) return null;
1058
1059 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001060 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001061 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001062 if (mNetworkInfo.isConnected()) {
1063 info.intent = mStatusIntent;
1064 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001065 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001066 }
1067
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001068 public VpnConfig getLegacyVpnConfig() {
1069 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001070 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001071 } else {
1072 return null;
1073 }
1074 }
1075
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001076 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001077 * Bringing up a VPN connection takes time, and that is all this thread
1078 * does. Here we have plenty of time. The only thing we need to take
1079 * care of is responding to interruptions as soon as possible. Otherwise
1080 * requests will be piled up. This can be done in a Handler as a state
1081 * machine, but it is much easier to read in the current form.
1082 */
1083 private class LegacyVpnRunner extends Thread {
1084 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001085
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001086 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001087 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001088 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001089 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001090 private final AtomicInteger mOuterConnection =
1091 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001092
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001093 private long mTimer = -1;
1094
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001095 /**
1096 * Watch for the outer connection (passing in the constructor) going away.
1097 */
1098 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1099 @Override
1100 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001101 if (!mEnableTeardown) return;
1102
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001103 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1104 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1105 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1106 NetworkInfo info = (NetworkInfo)intent.getExtra(
1107 ConnectivityManager.EXTRA_NETWORK_INFO);
1108 if (info != null && !info.isConnectedOrConnecting()) {
1109 try {
1110 mObserver.interfaceStatusChanged(mOuterInterface, false);
1111 } catch (RemoteException e) {}
1112 }
1113 }
1114 }
1115 }
1116 };
1117
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001118 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001119 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001120 mConfig = config;
1121 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001122 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001123 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001124 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001125
1126 // This is the interface which VPN is running on,
1127 // mConfig.interfaze will change to point to OUR
1128 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001129 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001130 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001131 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001132 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001133
Paul Jensene75b9e32015-04-06 11:54:53 -04001134 if (!TextUtils.isEmpty(mOuterInterface)) {
1135 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1136 for (Network network : cm.getAllNetworks()) {
1137 final LinkProperties lp = cm.getLinkProperties(network);
1138 if (lp != null && mOuterInterface.equals(lp.getInterfaceName())) {
1139 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1140 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1141 }
1142 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001143 }
1144
1145 IntentFilter filter = new IntentFilter();
1146 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1147 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001148 }
1149
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001150 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001151 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001152 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1153 exit();
1154 }
1155 }
1156
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001157 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001158 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001159 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001160 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001161 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001162 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001163 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001164 try {
1165 mContext.unregisterReceiver(mBroadcastReceiver);
1166 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001167 }
1168
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001169 @Override
1170 public void run() {
1171 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001172 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001173 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001174 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001175 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001176 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001177 }
1178 }
1179
1180 private void checkpoint(boolean yield) throws InterruptedException {
1181 long now = SystemClock.elapsedRealtime();
1182 if (mTimer == -1) {
1183 mTimer = now;
1184 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001185 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001186 Thread.sleep(yield ? 200 : 1);
1187 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001188 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001189 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001190 }
1191 }
1192
1193 private void execute() {
1194 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001195 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001196 try {
1197 // Initialize the timer.
1198 checkpoint(false);
1199
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001200 // Wait for the daemons to stop.
1201 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001202 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001203 checkpoint(true);
1204 }
1205 }
1206
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001207 // Clear the previous state.
1208 File state = new File("/data/misc/vpn/state");
1209 state.delete();
1210 if (state.exists()) {
1211 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001212 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001213 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001214 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001215
Chia-chi Yehe9107902011-07-02 01:48:50 -07001216 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001217 boolean restart = false;
1218 for (String[] arguments : mArguments) {
1219 restart = restart || (arguments != null);
1220 }
1221 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001222 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001223 return;
1224 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001225 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001226
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001227 // Start the daemon with arguments.
1228 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 String[] arguments = mArguments[i];
1230 if (arguments == null) {
1231 continue;
1232 }
1233
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001234 // Start the daemon.
1235 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001236 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001237
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001238 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001239 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001240 checkpoint(true);
1241 }
1242
1243 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001244 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001245 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001246 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001247
1248 // Wait for the socket to connect.
1249 while (true) {
1250 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001251 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001252 break;
1253 } catch (Exception e) {
1254 // ignore
1255 }
1256 checkpoint(true);
1257 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001258 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001259
1260 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001261 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001262 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001263 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001264 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001265 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001266 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001267 out.write(bytes.length >> 8);
1268 out.write(bytes.length);
1269 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001270 checkpoint(false);
1271 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001272 out.write(0xFF);
1273 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001274 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001275
1276 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001277 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001278 while (true) {
1279 try {
1280 if (in.read() == -1) {
1281 break;
1282 }
1283 } catch (Exception e) {
1284 // ignore
1285 }
1286 checkpoint(true);
1287 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001288 }
1289
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001290 // Wait for the daemons to create the new state.
1291 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001292 // Check if a running daemon is dead.
1293 for (int i = 0; i < mDaemons.length; ++i) {
1294 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001295 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001296 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001297 }
1298 }
1299 checkpoint(true);
1300 }
1301
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001302 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001303 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001304 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001305 throw new IllegalStateException("Cannot parse the state");
1306 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001307
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001308 // Set the interface and the addresses in the config.
1309 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001310
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001311 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001312 // Set the routes if they are not set in the config.
1313 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001314 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001315 }
1316
1317 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001318 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001319 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001320 if (!dnsServers.isEmpty()) {
1321 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1322 }
1323 }
1324
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001325 // Set the search domains if they are not set in the config.
1326 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1327 String searchDomains = parameters[4].trim();
1328 if (!searchDomains.isEmpty()) {
1329 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1330 }
1331 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001332
Lorenzo Colitti50262792014-09-19 01:53:35 +09001333 // Add a throw route for the VPN server endpoint, if one was specified.
1334 String endpoint = parameters[5];
1335 if (!endpoint.isEmpty()) {
1336 try {
1337 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1338 if (addr instanceof Inet4Address) {
1339 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1340 } else if (addr instanceof Inet6Address) {
1341 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1342 } else {
1343 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1344 }
1345 } catch (IllegalArgumentException e) {
1346 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1347 }
1348 }
1349
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001350 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001351 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001352 // Set the start time
1353 mConfig.startTime = SystemClock.elapsedRealtime();
1354
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001355 // Check if the thread is interrupted while we are waiting.
1356 checkpoint(false);
1357
Chia-chi Yehe9107902011-07-02 01:48:50 -07001358 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001359 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001360 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001361 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001362
1363 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001364 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001365 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001366
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001367 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001368
1369 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001370 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001371 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001372 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001373 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001374 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001375 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001376 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001377 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001378 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001379 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001380 }
1381 }
1382
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001383 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001384 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001385 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001386 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001387 }
1388 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001389
1390 /**
1391 * Monitor the daemons we started, moving to disconnected state if the
1392 * underlying services fail.
1393 */
1394 private void monitorDaemons() {
1395 if (!mNetworkInfo.isConnected()) {
1396 return;
1397 }
1398
1399 try {
1400 while (true) {
1401 Thread.sleep(2000);
1402 for (int i = 0; i < mDaemons.length; i++) {
1403 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1404 return;
1405 }
1406 }
1407 }
1408 } catch (InterruptedException e) {
1409 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1410 } finally {
1411 for (String daemon : mDaemons) {
1412 SystemService.stop(daemon);
1413 }
1414
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001415 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001416 }
1417 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001418 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001419}