blob: 6c1e1a7033009420cf596aa6c2a53691f8fb42a0 [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;
Jeff Sharkey899223b2012-08-04 15:24:58 -070023
Jeff Davidsonbc19c182014-11-11 13:20:01 -080024import android.Manifest;
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.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040035import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070036import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070037import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070038import android.net.ConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070039import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090040import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070041import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070042import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070043import android.net.LocalSocket;
44import android.net.LocalSocketAddress;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -080045import android.net.Network;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040046import android.net.NetworkAgent;
47import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070048import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040049import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070050import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070051import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040052import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070053import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080054import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070055import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070056import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040057import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070058import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070059import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070060import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070061import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070062import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070063import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070064import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070065import android.os.UserManager;
Robin Lee244ce8e2016-01-05 18:03:46 +000066import android.provider.Settings;
Jeff Sharkey82f85212012-08-24 11:17:25 -070067import android.security.Credentials;
68import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040069import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070070import android.util.Log;
71
Chad Brubakerc2865192013-07-10 14:46:23 -070072import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070073import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070074import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080075import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070076import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070077import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078
Jeff Davidson05542602014-08-11 14:07:27 -070079import libcore.io.IoUtils;
80
Chia-chi Yeh97a61562011-07-14 15:05:05 -070081import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070082import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070083import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070084import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070085import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070086import java.net.Inet6Address;
87import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070088import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040089import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070090import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040091import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040092import java.util.SortedSet;
93import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070094import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070095
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096/**
97 * @hide
98 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040099public class Vpn {
100 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700101 private static final String TAG = "Vpn";
102 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400103
Jeff Sharkey899223b2012-08-04 15:24:58 -0700104 // TODO: create separate trackers for each unique VPN to support
105 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700106
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400107 private Context mContext;
108 private NetworkInfo mNetworkInfo;
109 private String mPackage;
110 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700111 private String mInterface;
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;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400116 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700117 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400118 private NetworkAgent mNetworkAgent;
119 private final Looper mLooper;
120 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700121
122 /* list of users using this VPN. */
123 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400124 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700125
Paul Jensen0784eea2014-08-19 16:00:24 -0400126 // Handle of user initiating VPN.
127 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700128
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400130 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400132 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400133 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400134 mLooper = looper;
135
136 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400137 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700138
139 try {
140 netService.registerObserver(mObserver);
141 } catch (RemoteException e) {
142 Log.wtf(TAG, "Problem registering observer", e);
143 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400144
145 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
146 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
147 mNetworkCapabilities = new NetworkCapabilities();
148 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
149 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700150 }
151
Jeff Sharkey57666932013-04-30 17:01:57 -0700152 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700153 * Set if this object is responsible for watching for {@link NetworkInfo}
154 * teardown. When {@code false}, teardown is handled externally by someone
155 * else.
156 */
157 public void setEnableTeardown(boolean enableTeardown) {
158 mEnableTeardown = enableTeardown;
159 }
160
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 /**
162 * Update current state, dispaching event to listeners.
163 */
164 private void updateState(DetailedState detailedState, String reason) {
165 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
166 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400167 if (mNetworkAgent != null) {
168 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
169 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700170 }
171
172 /**
Robin Lee244ce8e2016-01-05 18:03:46 +0000173 * Configures an always-on VPN connection through a specific application.
174 * This connection is automatically granted and persisted after a reboot.
175 *
176 * <p>The designated package should exist and declare a {@link VpnService} in its
177 * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
178 * otherwise the call will fail.
179 *
180 * @param newPackage the package to designate as always-on VPN supplier.
181 */
182 public synchronized boolean setAlwaysOnPackage(String packageName) {
183 enforceControlPermissionOrInternalCaller();
184
185 // Disconnect current VPN.
186 prepareInternal(VpnConfig.LEGACY_VPN);
187
188 // Pre-authorize new always-on VPN package.
189 if (packageName != null) {
190 if (!setPackageAuthorization(packageName, true)) {
191 return false;
192 }
Robin Lee78378842016-02-12 11:51:33 +0000193 prepareInternal(packageName);
Robin Lee244ce8e2016-01-05 18:03:46 +0000194 }
195
196 // Save the new package name in Settings.Secure.
197 final long token = Binder.clearCallingIdentity();
198 try {
199 Settings.Secure.putStringForUser(mContext.getContentResolver(),
200 Settings.Secure.ALWAYS_ON_VPN_APP, packageName, mUserHandle);
201 } finally {
202 Binder.restoreCallingIdentity(token);
203 }
204 return true;
205 }
206
207 /**
208 * @return the package name of the VPN controller responsible for always-on VPN,
209 * or {@code null} if none is set or always-on VPN is controlled through
210 * lockdown instead.
211 * @hide
212 */
213 public synchronized String getAlwaysOnPackage() {
214 enforceControlPermissionOrInternalCaller();
215
216 final long token = Binder.clearCallingIdentity();
217 try {
218 return Settings.Secure.getStringForUser(mContext.getContentResolver(),
219 Settings.Secure.ALWAYS_ON_VPN_APP, mUserHandle);
220 } finally {
221 Binder.restoreCallingIdentity(token);
222 }
223 }
224
225 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700226 * Prepare for a VPN application. This method is designed to solve
227 * race conditions. It first compares the current prepared package
228 * with {@code oldPackage}. If they are the same, the prepared
229 * package is revoked and replaced with {@code newPackage}. If
230 * {@code oldPackage} is {@code null}, the comparison is omitted.
231 * If {@code newPackage} is the same package or {@code null}, the
232 * revocation is omitted. This method returns {@code true} if the
233 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700234 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700235 * Legacy VPN is handled specially since it is not a real package.
236 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
237 * it can be revoked by itself.
238 *
239 * @param oldPackage The package name of the old VPN application.
240 * @param newPackage The package name of the new VPN application.
241 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700242 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700243 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700244 if (oldPackage != null) {
245 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
246 // The package doesn't match. We return false (to obtain user consent) unless the
247 // user has already consented to that VPN package.
248 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
249 prepareInternal(oldPackage);
250 return true;
251 }
252 return false;
253 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
254 && !isVpnUserPreConsented(oldPackage)) {
255 // Currently prepared VPN is revoked, so unprepare it and return false.
256 prepareInternal(VpnConfig.LEGACY_VPN);
257 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700258 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700259 }
260
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700261 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700262 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
263 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700264 return true;
265 }
266
Robin Lee1b1bcd72016-02-12 18:11:30 +0000267 // Stop an existing always-on VPN from being dethroned by other apps.
268 if (getAlwaysOnPackage() != null) {
269 return false;
270 }
271
272 // Check that the caller is authorized.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700273 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700274
Jeff Davidson11008a72014-11-20 13:12:46 -0800275 prepareInternal(newPackage);
276 return true;
277 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700278
Jeff Davidson11008a72014-11-20 13:12:46 -0800279 /** Prepare the VPN for the given package. Does not perform permission checks. */
280 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400281 long token = Binder.clearCallingIdentity();
282 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800283 // Reset the interface.
284 if (mInterface != null) {
285 mStatusIntent = null;
286 agentDisconnect();
287 jniReset(mInterface);
288 mInterface = null;
289 mVpnUsers = null;
290 }
291
292 // Revoke the connection or stop LegacyVpnRunner.
293 if (mConnection != null) {
294 try {
295 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
296 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
297 } catch (Exception e) {
298 // ignore
299 }
300 mContext.unbindService(mConnection);
301 mConnection = null;
302 } else if (mLegacyVpnRunner != null) {
303 mLegacyVpnRunner.exit();
304 mLegacyVpnRunner = null;
305 }
306
307 try {
308 mNetd.denyProtect(mOwnerUID);
309 } catch (Exception e) {
310 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
311 }
312
313 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
314 mPackage = newPackage;
315 mOwnerUID = getAppUid(newPackage, mUserHandle);
316 try {
317 mNetd.allowProtect(mOwnerUID);
318 } catch (Exception e) {
319 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
320 }
321 mConfig = null;
322
323 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400324 } finally {
325 Binder.restoreCallingIdentity(token);
326 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700327 }
328
Jeff Davidson05542602014-08-11 14:07:27 -0700329 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100330 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700331 */
Robin Lee244ce8e2016-01-05 18:03:46 +0000332 public boolean setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700333 // Check if the caller is authorized.
Robin Lee244ce8e2016-01-05 18:03:46 +0000334 enforceControlPermissionOrInternalCaller();
Jeff Davidson05542602014-08-11 14:07:27 -0700335
Robin Lee3b3dd942015-05-12 18:14:58 +0100336 int uid = getAppUid(packageName, mUserHandle);
337 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
338 // Authorization for nonexistent packages (or fake ones) can't be updated.
Robin Lee244ce8e2016-01-05 18:03:46 +0000339 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700340 }
341
342 long token = Binder.clearCallingIdentity();
343 try {
344 AppOpsManager appOps =
345 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100346 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700347 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Robin Lee244ce8e2016-01-05 18:03:46 +0000348 return true;
Jeff Davidson05542602014-08-11 14:07:27 -0700349 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100350 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700351 } finally {
352 Binder.restoreCallingIdentity(token);
353 }
Robin Lee244ce8e2016-01-05 18:03:46 +0000354 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700355 }
356
357 private boolean isVpnUserPreConsented(String packageName) {
358 AppOpsManager appOps =
359 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
360
361 // Verify that the caller matches the given package and has permission to activate VPNs.
362 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
363 packageName) == AppOpsManager.MODE_ALLOWED;
364 }
365
Paul Jensen0784eea2014-08-19 16:00:24 -0400366 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700367 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700369 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400370 PackageManager pm = mContext.getPackageManager();
371 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700372 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700373 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400374 } catch (NameNotFoundException e) {
375 result = -1;
376 }
377 return result;
378 }
379
380 public NetworkInfo getNetworkInfo() {
381 return mNetworkInfo;
382 }
383
Paul Jensen31a94f42015-02-13 14:18:39 -0500384 public int getNetId() {
385 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
386 }
387
Lorenzo Colitti60446162014-09-20 00:14:31 +0900388 private LinkProperties makeLinkProperties() {
389 boolean allowIPv4 = mConfig.allowIPv4;
390 boolean allowIPv6 = mConfig.allowIPv6;
391
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400392 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900393
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400394 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700395
Lorenzo Colitti60446162014-09-20 00:14:31 +0900396 if (mConfig.addresses != null) {
397 for (LinkAddress address : mConfig.addresses) {
398 lp.addLinkAddress(address);
399 allowIPv4 |= address.getAddress() instanceof Inet4Address;
400 allowIPv6 |= address.getAddress() instanceof Inet6Address;
401 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400402 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900403
404 if (mConfig.routes != null) {
405 for (RouteInfo route : mConfig.routes) {
406 lp.addRoute(route);
407 InetAddress address = route.getDestination().getAddress();
408 allowIPv4 |= address instanceof Inet4Address;
409 allowIPv6 |= address instanceof Inet6Address;
410 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400411 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700412
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400413 if (mConfig.dnsServers != null) {
414 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700415 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
416 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900417 allowIPv4 |= address instanceof Inet4Address;
418 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400419 }
420 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700421
Lorenzo Colitti60446162014-09-20 00:14:31 +0900422 if (!allowIPv4) {
423 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
424 }
425 if (!allowIPv6) {
426 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
427 }
428
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400429 // Concatenate search domains into a string.
430 StringBuilder buffer = new StringBuilder();
431 if (mConfig.searchDomains != null) {
432 for (String domain : mConfig.searchDomains) {
433 buffer.append(domain).append(' ');
434 }
435 }
436 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700437
Lorenzo Colitti60446162014-09-20 00:14:31 +0900438 // TODO: Stop setting the MTU in jniCreate and set it here.
439
440 return lp;
441 }
442
443 private void agentConnect() {
444 LinkProperties lp = makeLinkProperties();
445
446 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
447 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
448 } else {
449 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
450 }
451
Robin Lee323f29d2016-05-04 16:38:06 +0100452 mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700453
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700454 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700455 networkMisc.allowBypass = mConfig.allowBypass;
456
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400457 long token = Binder.clearCallingIdentity();
458 try {
459 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700460 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700461 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400462 public void unwanted() {
463 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700464 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400465 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700466 } finally {
467 Binder.restoreCallingIdentity(token);
468 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700469
Paul Jensen0784eea2014-08-19 16:00:24 -0400470 addVpnUserLocked(mUserHandle);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700471 // If the user can have restricted profiles, assign all its restricted profiles to this VPN
472 if (canHaveRestrictedProfile(mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400473 token = Binder.clearCallingIdentity();
474 List<UserInfo> users;
475 try {
476 users = UserManager.get(mContext).getUsers();
477 } finally {
478 Binder.restoreCallingIdentity(token);
479 }
480 for (UserInfo user : users) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700481 if (user.isRestricted() && (user.restrictedProfileParentId == mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400482 addVpnUserLocked(user.id);
483 }
484 }
485 }
486 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
Robin Lee323f29d2016-05-04 16:38:06 +0100487
488 mNetworkInfo.setIsAvailable(true);
489 updateState(DetailedState.CONNECTED, "agentConnect");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400490 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700491
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700492 private boolean canHaveRestrictedProfile(int userId) {
493 long token = Binder.clearCallingIdentity();
494 try {
495 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
496 } finally {
497 Binder.restoreCallingIdentity(token);
498 }
499 }
500
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400501 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
502 networkInfo.setIsAvailable(false);
503 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
504 if (networkAgent != null) {
505 networkAgent.sendNetworkInfo(networkInfo);
506 }
507 }
508
509 private void agentDisconnect(NetworkAgent networkAgent) {
510 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
511 agentDisconnect(networkInfo, networkAgent);
512 }
513
514 private void agentDisconnect() {
515 if (mNetworkInfo.isConnected()) {
516 agentDisconnect(mNetworkInfo, mNetworkAgent);
517 mNetworkAgent = null;
518 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700519 }
520
521 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700522 * Establish a VPN network and return the file descriptor of the VPN
523 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700524 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700525 *
526 * @param config The parameters to configure the network.
527 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700528 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700529 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700530 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700531 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400532 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700533 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700534 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700535 // Check to ensure consent hasn't been revoked since we were prepared.
536 if (!isVpnUserPreConsented(mPackage)) {
537 return null;
538 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700539 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700540 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
541 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700542 long token = Binder.clearCallingIdentity();
543 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700544 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400545 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000546 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
547 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700548 throw new SecurityException("Restricted users cannot establish VPNs");
549 }
550
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700551 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400552 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700553 if (info == null) {
554 throw new SecurityException("Cannot find " + config.user);
555 }
556 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
557 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
558 }
559 } catch (RemoteException e) {
560 throw new SecurityException("Cannot find " + config.user);
561 } finally {
562 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700563 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700564
Chad Brubaker850eb672014-03-21 21:02:47 +0000565 // Save the old config in case we need to go back.
566 VpnConfig oldConfig = mConfig;
567 String oldInterface = mInterface;
568 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 NetworkAgent oldNetworkAgent = mNetworkAgent;
570 mNetworkAgent = null;
571 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000572
Chia-chi Yehe9107902011-07-02 01:48:50 -0700573 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700574 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700575 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700576 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700577 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700578
Chad Brubakerc2865192013-07-10 14:46:23 -0700579 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700580 StringBuilder builder = new StringBuilder();
581 for (LinkAddress address : config.addresses) {
582 builder.append(" " + address);
583 }
584 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700585 throw new IllegalArgumentException("At least one address must be specified");
586 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700587 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700588 if (!mContext.bindServiceAsUser(intent, connection,
589 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
590 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700591 throw new IllegalStateException("Cannot bind " + config.user);
592 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000593
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700594 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700595 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700596
597 // Fill more values.
598 config.user = mPackage;
599 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700600 config.startTime = SystemClock.elapsedRealtime();
601 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000602
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700603 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400604 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700605
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400606 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000607
608 if (oldConnection != null) {
609 mContext.unbindService(oldConnection);
610 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400611 // Remove the old tun's user forwarding rules
612 // The new tun's user rules have already been added so they will take over
613 // as rules are deleted. This prevents data leakage as the rules are moved over.
614 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000615 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000616 jniReset(oldInterface);
617 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700618
619 try {
620 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
621 } catch (IOException e) {
622 throw new IllegalStateException(
623 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
624 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000625 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000626 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400627 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000628 // restore old state
629 mConfig = oldConfig;
630 mConnection = oldConnection;
631 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400632 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000633 mInterface = oldInterface;
634 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700635 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000636 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700637 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700638 }
639
Chad Brubakerc2865192013-07-10 14:46:23 -0700640 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800641 return mNetworkAgent != null && mInterface != null;
642 }
643
644 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
645 // that a call to mutate VPN state is admissible.
646 private boolean isCallerEstablishedOwnerLocked() {
647 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700648 }
649
Paul Jensen0784eea2014-08-19 16:00:24 -0400650 // Note: Return type guarantees results are deduped and sorted, which callers require.
651 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
652 SortedSet<Integer> uids = new TreeSet<Integer>();
653 for (String app : packageNames) {
654 int uid = getAppUid(app, userHandle);
655 if (uid != -1) uids.add(uid);
656 }
657 return uids;
658 }
659
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400660 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400661 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800662 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700663 throw new IllegalStateException("VPN is not active");
664 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700665
Paul Jensen0784eea2014-08-19 16:00:24 -0400666 if (mConfig.allowedApplications != null) {
667 // Add ranges covering all UIDs for allowedApplications.
668 int start = -1, stop = -1;
669 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
670 if (start == -1) {
671 start = uid;
672 } else if (uid != stop + 1) {
673 mVpnUsers.add(new UidRange(start, stop));
674 start = uid;
675 }
676 stop = uid;
677 }
678 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
679 } else if (mConfig.disallowedApplications != null) {
680 // Add all ranges for user skipping UIDs for disallowedApplications.
681 final UidRange userRange = UidRange.createForUser(userHandle);
682 int start = userRange.start;
683 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
684 if (uid == start) {
685 start++;
686 } else {
687 mVpnUsers.add(new UidRange(start, uid - 1));
688 start = uid + 1;
689 }
690 }
691 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
692 } else {
693 // Add all UIDs for the user.
694 mVpnUsers.add(UidRange.createForUser(userHandle));
695 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700696
697 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700698 }
699
Paul Jensen0784eea2014-08-19 16:00:24 -0400700 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
701 // apply to userHandle.
702 private List<UidRange> uidRangesForUser(int userHandle) {
703 final UidRange userRange = UidRange.createForUser(userHandle);
704 final List<UidRange> ranges = new ArrayList<UidRange>();
705 for (UidRange range : mVpnUsers) {
706 if (range.start >= userRange.start && range.stop <= userRange.stop) {
707 ranges.add(range);
708 }
709 }
710 return ranges;
711 }
712
713 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800714 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700715 throw new IllegalStateException("VPN is not active");
716 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400717 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700718 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400719 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700720 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400721 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700722 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700723 }
724
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700725 public void onUserAdded(int userHandle) {
726 // If the user is restricted tie them to the parent user's VPN
727 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Fyodor Kupolov49d5a012016-03-04 13:41:58 -0800728 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle
729 && mVpnUsers != null) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700730 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700731 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400732 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400733 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400734 final List<UidRange> ranges = uidRangesForUser(userHandle);
735 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400736 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700737 } catch (Exception e) {
738 Log.wtf(TAG, "Failed to add restricted user to owner", e);
739 }
740 }
741 }
742 }
743
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700744 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700745 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700746 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
Fyodor Kupolov49d5a012016-03-04 13:41:58 -0800747 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle
748 && mVpnUsers != null) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700749 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700750 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400751 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700752 } catch (Exception e) {
753 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
754 }
755 }
756 }
757 }
758
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700759 /**
760 * Return the configuration of the currently running VPN.
761 */
762 public VpnConfig getVpnConfig() {
763 enforceControlPermission();
764 return mConfig;
765 }
766
Jeff Sharkey899223b2012-08-04 15:24:58 -0700767 @Deprecated
768 public synchronized void interfaceStatusChanged(String iface, boolean up) {
769 try {
770 mObserver.interfaceStatusChanged(iface, up);
771 } catch (RemoteException e) {
772 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700773 }
774 }
775
Jeff Sharkey899223b2012-08-04 15:24:58 -0700776 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
777 @Override
778 public void interfaceStatusChanged(String interfaze, boolean up) {
779 synchronized (Vpn.this) {
780 if (!up && mLegacyVpnRunner != null) {
781 mLegacyVpnRunner.check(interfaze);
782 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700783 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700784 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700785
Jeff Sharkey899223b2012-08-04 15:24:58 -0700786 @Override
787 public void interfaceRemoved(String interfaze) {
788 synchronized (Vpn.this) {
789 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700790 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400791 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500792 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700793 mInterface = null;
794 if (mConnection != null) {
795 mContext.unbindService(mConnection);
796 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400797 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700798 } else if (mLegacyVpnRunner != null) {
799 mLegacyVpnRunner.exit();
800 mLegacyVpnRunner = null;
801 }
802 }
803 }
804 }
805 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700806
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700807 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800808 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700809 }
810
Robin Lee244ce8e2016-01-05 18:03:46 +0000811 private void enforceControlPermissionOrInternalCaller() {
812 // Require caller to be either an application with CONTROL_VPN permission or a process
813 // in the system server.
814 mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
815 "Unauthorized Caller");
816 }
817
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700818 private class Connection implements ServiceConnection {
819 private IBinder mService;
820
821 @Override
822 public void onServiceConnected(ComponentName name, IBinder service) {
823 mService = service;
824 }
825
826 @Override
827 public void onServiceDisconnected(ComponentName name) {
828 mService = null;
829 }
830 }
831
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700832 private void prepareStatusIntent() {
833 final long token = Binder.clearCallingIdentity();
834 try {
835 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
836 } finally {
837 Binder.restoreCallingIdentity(token);
838 }
839 }
840
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700841 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800842 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700843 return false;
844 }
845 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800846 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700847 return success;
848 }
849
850 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800851 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700852 return false;
853 }
854 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800855 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700856 return success;
857 }
858
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800859 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
860 if (!isCallerEstablishedOwnerLocked()) {
861 return false;
862 }
863 if (networks == null) {
864 mConfig.underlyingNetworks = null;
865 } else {
866 mConfig.underlyingNetworks = new Network[networks.length];
867 for (int i = 0; i < networks.length; ++i) {
868 if (networks[i] == null) {
869 mConfig.underlyingNetworks[i] = null;
870 } else {
871 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
872 }
873 }
874 }
875 return true;
876 }
877
878 public synchronized Network[] getUnderlyingNetworks() {
879 if (!isRunningLocked()) {
880 return null;
881 }
882 return mConfig.underlyingNetworks;
883 }
884
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800885 /**
886 * This method should only be called by ConnectivityService. Because it doesn't
887 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
888 */
889 public synchronized VpnInfo getVpnInfo() {
890 if (!isRunningLocked()) {
891 return null;
892 }
893
894 VpnInfo info = new VpnInfo();
895 info.ownerUid = mOwnerUID;
896 info.vpnIface = mInterface;
897 return info;
898 }
899
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800900 public synchronized boolean appliesToUid(int uid) {
901 if (!isRunningLocked()) {
902 return false;
903 }
904 for (UidRange uidRange : mVpnUsers) {
905 if (uidRange.start <= uid && uid <= uidRange.stop) {
906 return true;
907 }
908 }
909 return false;
910 }
911
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700912 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700913 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700914 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700915 private native void jniReset(String interfaze);
916 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700917 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
918 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700919
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900920 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
921 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700922 // Currently legacy VPN only works on IPv4.
923 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900924 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700925 }
926 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700927
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900928 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700929 }
930
931 /**
932 * Start legacy VPN, controlling native daemons as needed. Creates a
933 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800934 *
935 * Should only be called to respond to Binder requests as this enforces caller permission. Use
936 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
937 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700938 */
939 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800940 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800941 long token = Binder.clearCallingIdentity();
942 try {
943 startLegacyVpnPrivileged(profile, keyStore, egress);
944 } finally {
945 Binder.restoreCallingIdentity(token);
946 }
947 }
948
949 /**
950 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
951 * permissions under the assumption that the caller is the system.
952 *
953 * Callers are responsible for checking permissions if needed.
954 */
955 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
956 LinkProperties egress) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400957 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400958 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000959 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
960 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400961 throw new SecurityException("Restricted users cannot establish VPNs");
962 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700963
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900964 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
965 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
966 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700967
968 // Load certificates.
969 String privateKey = "";
970 String userCert = "";
971 String caCert = "";
972 String serverCert = "";
973 if (!profile.ipsecUserCert.isEmpty()) {
974 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
975 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700976 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700977 }
978 if (!profile.ipsecCaCert.isEmpty()) {
979 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700980 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700981 }
982 if (!profile.ipsecServerCert.isEmpty()) {
983 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700984 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700985 }
986 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
987 throw new IllegalStateException("Cannot load credentials");
988 }
989
990 // Prepare arguments for racoon.
991 String[] racoon = null;
992 switch (profile.type) {
993 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
994 racoon = new String[] {
995 iface, profile.server, "udppsk", profile.ipsecIdentifier,
996 profile.ipsecSecret, "1701",
997 };
998 break;
999 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1000 racoon = new String[] {
1001 iface, profile.server, "udprsa", privateKey, userCert,
1002 caCert, serverCert, "1701",
1003 };
1004 break;
1005 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1006 racoon = new String[] {
1007 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1008 profile.ipsecSecret, profile.username, profile.password, "", gateway,
1009 };
1010 break;
1011 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1012 racoon = new String[] {
1013 iface, profile.server, "xauthrsa", privateKey, userCert,
1014 caCert, serverCert, profile.username, profile.password, "", gateway,
1015 };
1016 break;
1017 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1018 racoon = new String[] {
1019 iface, profile.server, "hybridrsa",
1020 caCert, serverCert, profile.username, profile.password, "", gateway,
1021 };
1022 break;
1023 }
1024
1025 // Prepare arguments for mtpd.
1026 String[] mtpd = null;
1027 switch (profile.type) {
1028 case VpnProfile.TYPE_PPTP:
1029 mtpd = new String[] {
1030 iface, "pptp", profile.server, "1723",
1031 "name", profile.username, "password", profile.password,
1032 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1033 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1034 (profile.mppe ? "+mppe" : "nomppe"),
1035 };
1036 break;
1037 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1038 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1039 mtpd = new String[] {
1040 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1041 "name", profile.username, "password", profile.password,
1042 "linkname", "vpn", "refuse-eap", "nodefaultroute",
1043 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1044 };
1045 break;
1046 }
1047
1048 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001049 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -07001050 config.user = profile.key;
1051 config.interfaze = iface;
1052 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001053
1054 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -07001055 if (!profile.dnsServers.isEmpty()) {
1056 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1057 }
1058 if (!profile.searchDomains.isEmpty()) {
1059 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1060 }
Jeff Sharkey82f85212012-08-24 11:17:25 -07001061 startLegacyVpn(config, racoon, mtpd);
1062 }
1063
1064 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001065 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001066
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001067 // Prepare for the new request.
1068 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001069 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001071 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001072 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1073 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001074 }
1075
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001076 /** Stop legacy VPN. Permissions must be checked by callers. */
1077 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001078 if (mLegacyVpnRunner != null) {
1079 mLegacyVpnRunner.exit();
1080 mLegacyVpnRunner = null;
1081
1082 synchronized (LegacyVpnRunner.TAG) {
1083 // wait for old thread to completely finish before spinning up
1084 // new instance, otherwise state updates can be out of order.
1085 }
1086 }
1087 }
1088
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001089 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001090 * Return the information of the current ongoing legacy VPN.
1091 */
1092 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001093 // Check if the caller is authorized.
1094 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001095 return getLegacyVpnInfoPrivileged();
1096 }
1097
1098 /**
1099 * Return the information of the current ongoing legacy VPN.
1100 * Callers are responsible for checking permissions if needed.
1101 */
1102 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001103 if (mLegacyVpnRunner == null) return null;
1104
1105 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001106 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001107 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001108 if (mNetworkInfo.isConnected()) {
1109 info.intent = mStatusIntent;
1110 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001111 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001112 }
1113
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001114 public VpnConfig getLegacyVpnConfig() {
1115 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001116 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001117 } else {
1118 return null;
1119 }
1120 }
1121
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001122 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001123 * Bringing up a VPN connection takes time, and that is all this thread
1124 * does. Here we have plenty of time. The only thing we need to take
1125 * care of is responding to interruptions as soon as possible. Otherwise
1126 * requests will be piled up. This can be done in a Handler as a state
1127 * machine, but it is much easier to read in the current form.
1128 */
1129 private class LegacyVpnRunner extends Thread {
1130 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001131
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001132 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001133 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001134 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001135 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001136 private final AtomicInteger mOuterConnection =
1137 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001138
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001139 private long mTimer = -1;
1140
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001141 /**
1142 * Watch for the outer connection (passing in the constructor) going away.
1143 */
1144 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1145 @Override
1146 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001147 if (!mEnableTeardown) return;
1148
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001149 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1150 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1151 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1152 NetworkInfo info = (NetworkInfo)intent.getExtra(
1153 ConnectivityManager.EXTRA_NETWORK_INFO);
1154 if (info != null && !info.isConnectedOrConnecting()) {
1155 try {
1156 mObserver.interfaceStatusChanged(mOuterInterface, false);
1157 } catch (RemoteException e) {}
1158 }
1159 }
1160 }
1161 }
1162 };
1163
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001164 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001165 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001166 mConfig = config;
1167 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001168 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001169 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001170 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001171
1172 // This is the interface which VPN is running on,
1173 // mConfig.interfaze will change to point to OUR
1174 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001175 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001176 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001177 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001178 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001179
Paul Jensene75b9e32015-04-06 11:54:53 -04001180 if (!TextUtils.isEmpty(mOuterInterface)) {
1181 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1182 for (Network network : cm.getAllNetworks()) {
1183 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001184 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001185 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1186 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1187 }
1188 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001189 }
1190
1191 IntentFilter filter = new IntentFilter();
1192 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1193 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001194 }
1195
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001196 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001197 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001198 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1199 exit();
1200 }
1201 }
1202
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001203 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001204 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001205 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001206 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001207 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001208 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001209 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001210 try {
1211 mContext.unregisterReceiver(mBroadcastReceiver);
1212 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001213 }
1214
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001215 @Override
1216 public void run() {
1217 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001218 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001219 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001220 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001221 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001222 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001223 }
1224 }
1225
1226 private void checkpoint(boolean yield) throws InterruptedException {
1227 long now = SystemClock.elapsedRealtime();
1228 if (mTimer == -1) {
1229 mTimer = now;
1230 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001231 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001232 Thread.sleep(yield ? 200 : 1);
1233 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001234 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001235 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001236 }
1237 }
1238
1239 private void execute() {
1240 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001241 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001242 try {
1243 // Initialize the timer.
1244 checkpoint(false);
1245
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001246 // Wait for the daemons to stop.
1247 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001248 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001249 checkpoint(true);
1250 }
1251 }
1252
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001253 // Clear the previous state.
1254 File state = new File("/data/misc/vpn/state");
1255 state.delete();
1256 if (state.exists()) {
1257 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001258 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001259 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001260 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001261
Chia-chi Yehe9107902011-07-02 01:48:50 -07001262 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001263 boolean restart = false;
1264 for (String[] arguments : mArguments) {
1265 restart = restart || (arguments != null);
1266 }
1267 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001268 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001269 return;
1270 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001271 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001272
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001273 // Start the daemon with arguments.
1274 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001275 String[] arguments = mArguments[i];
1276 if (arguments == null) {
1277 continue;
1278 }
1279
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001280 // Start the daemon.
1281 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001282 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001283
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001284 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001285 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001286 checkpoint(true);
1287 }
1288
1289 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001290 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001291 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001292 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001293
1294 // Wait for the socket to connect.
1295 while (true) {
1296 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001297 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001298 break;
1299 } catch (Exception e) {
1300 // ignore
1301 }
1302 checkpoint(true);
1303 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001304 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001305
1306 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001307 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001308 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001309 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001310 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001311 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001312 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001313 out.write(bytes.length >> 8);
1314 out.write(bytes.length);
1315 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001316 checkpoint(false);
1317 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001318 out.write(0xFF);
1319 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001320 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001321
1322 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001323 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001324 while (true) {
1325 try {
1326 if (in.read() == -1) {
1327 break;
1328 }
1329 } catch (Exception e) {
1330 // ignore
1331 }
1332 checkpoint(true);
1333 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001334 }
1335
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001336 // Wait for the daemons to create the new state.
1337 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001338 // Check if a running daemon is dead.
1339 for (int i = 0; i < mDaemons.length; ++i) {
1340 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001341 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001342 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001343 }
1344 }
1345 checkpoint(true);
1346 }
1347
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001348 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001349 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001350 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001351 throw new IllegalStateException("Cannot parse the state");
1352 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001353
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001354 // Set the interface and the addresses in the config.
1355 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001356
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001357 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001358 // Set the routes if they are not set in the config.
1359 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001360 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001361 }
1362
1363 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001364 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001365 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001366 if (!dnsServers.isEmpty()) {
1367 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1368 }
1369 }
1370
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001371 // Set the search domains if they are not set in the config.
1372 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1373 String searchDomains = parameters[4].trim();
1374 if (!searchDomains.isEmpty()) {
1375 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1376 }
1377 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001378
Lorenzo Colitti50262792014-09-19 01:53:35 +09001379 // Add a throw route for the VPN server endpoint, if one was specified.
1380 String endpoint = parameters[5];
1381 if (!endpoint.isEmpty()) {
1382 try {
1383 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1384 if (addr instanceof Inet4Address) {
1385 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1386 } else if (addr instanceof Inet6Address) {
1387 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1388 } else {
1389 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1390 }
1391 } catch (IllegalArgumentException e) {
1392 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1393 }
1394 }
1395
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001396 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001397 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001398 // Set the start time
1399 mConfig.startTime = SystemClock.elapsedRealtime();
1400
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001401 // Check if the thread is interrupted while we are waiting.
1402 checkpoint(false);
1403
Chia-chi Yehe9107902011-07-02 01:48:50 -07001404 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001405 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001406 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001407 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001408
1409 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001410 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001411 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001412
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001413 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001414
1415 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001416 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001417 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001418 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001419 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001420 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001421 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001422 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001423 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001424 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001425 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001426 }
1427 }
1428
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001429 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001430 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001431 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001432 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001433 }
1434 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001435
1436 /**
1437 * Monitor the daemons we started, moving to disconnected state if the
1438 * underlying services fail.
1439 */
1440 private void monitorDaemons() {
1441 if (!mNetworkInfo.isConnected()) {
1442 return;
1443 }
1444
1445 try {
1446 while (true) {
1447 Thread.sleep(2000);
1448 for (int i = 0; i < mDaemons.length; i++) {
1449 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1450 return;
1451 }
1452 }
1453 }
1454 } catch (InterruptedException e) {
1455 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1456 } finally {
1457 for (String daemon : mDaemons) {
1458 SystemService.stop(daemon);
1459 }
1460
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001461 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001462 }
1463 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001464 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001465}