blob: 5bd4f987073efe4461194928382d5c21854bc99a [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;
Jeff Sharkey82f85212012-08-24 11:17:25 -070066import android.security.Credentials;
67import android.security.KeyStore;
Paul Jensene75b9e32015-04-06 11:54:53 -040068import android.text.TextUtils;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070069import android.util.Log;
70
Chad Brubakerc2865192013-07-10 14:46:23 -070071import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070072import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070073import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080074import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070075import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070076import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070077
Jeff Davidson05542602014-08-11 14:07:27 -070078import libcore.io.IoUtils;
79
Chia-chi Yeh97a61562011-07-14 15:05:05 -070080import java.io.File;
Jeff Davidson6bbf39c2014-07-23 10:14:53 -070081import java.io.IOException;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070082import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070083import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070084import java.net.Inet4Address;
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -070085import java.net.Inet6Address;
86import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070087import java.nio.charset.StandardCharsets;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040088import java.util.ArrayList;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070089import java.util.Arrays;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040090import java.util.List;
Paul Jensen0784eea2014-08-19 16:00:24 -040091import java.util.SortedSet;
92import java.util.TreeSet;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070093import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070094
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070095/**
96 * @hide
97 */
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040098public class Vpn {
99 private static final String NETWORKTYPE = "VPN";
Jeff Sharkey899223b2012-08-04 15:24:58 -0700100 private static final String TAG = "Vpn";
101 private static final boolean LOGD = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400102
Jeff Sharkey899223b2012-08-04 15:24:58 -0700103 // TODO: create separate trackers for each unique VPN to support
104 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700105
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106 private Context mContext;
107 private NetworkInfo mNetworkInfo;
108 private String mPackage;
109 private int mOwnerUID;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700110 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700111 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700112 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700113 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700114 private volatile boolean mEnableTeardown = true;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400115 private final INetworkManagementService mNetd;
Chad Brubakerc2865192013-07-10 14:46:23 -0700116 private VpnConfig mConfig;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400117 private NetworkAgent mNetworkAgent;
118 private final Looper mLooper;
119 private final NetworkCapabilities mNetworkCapabilities;
Chad Brubakerc2865192013-07-10 14:46:23 -0700120
121 /* list of users using this VPN. */
122 @GuardedBy("this")
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400123 private List<UidRange> mVpnUsers = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700124
Paul Jensen0784eea2014-08-19 16:00:24 -0400125 // Handle of user initiating VPN.
126 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400128 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensene75b9e32015-04-06 11:54:53 -0400129 int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400131 mNetd = netService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400132 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400133 mLooper = looper;
134
135 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400136 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700137
138 try {
139 netService.registerObserver(mObserver);
140 } catch (RemoteException e) {
141 Log.wtf(TAG, "Problem registering observer", e);
142 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400143
144 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
145 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
146 mNetworkCapabilities = new NetworkCapabilities();
147 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
148 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700149 }
150
Jeff Sharkey57666932013-04-30 17:01:57 -0700151 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700152 * Set if this object is responsible for watching for {@link NetworkInfo}
153 * teardown. When {@code false}, teardown is handled externally by someone
154 * else.
155 */
156 public void setEnableTeardown(boolean enableTeardown) {
157 mEnableTeardown = enableTeardown;
158 }
159
Jeff Sharkey899223b2012-08-04 15:24:58 -0700160 /**
161 * Update current state, dispaching event to listeners.
162 */
163 private void updateState(DetailedState detailedState, String reason) {
164 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
165 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400166 if (mNetworkAgent != null) {
167 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
168 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700169 }
170
171 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700172 * Prepare for a VPN application. This method is designed to solve
173 * race conditions. It first compares the current prepared package
174 * with {@code oldPackage}. If they are the same, the prepared
175 * package is revoked and replaced with {@code newPackage}. If
176 * {@code oldPackage} is {@code null}, the comparison is omitted.
177 * If {@code newPackage} is the same package or {@code null}, the
178 * revocation is omitted. This method returns {@code true} if the
179 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700180 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700181 * Legacy VPN is handled specially since it is not a real package.
182 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
183 * it can be revoked by itself.
184 *
185 * @param oldPackage The package name of the old VPN application.
186 * @param newPackage The package name of the new VPN application.
187 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700188 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700189 public synchronized boolean prepare(String oldPackage, String newPackage) {
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700190 if (oldPackage != null) {
191 if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
192 // The package doesn't match. We return false (to obtain user consent) unless the
193 // user has already consented to that VPN package.
194 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
195 prepareInternal(oldPackage);
196 return true;
197 }
198 return false;
199 } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
200 && !isVpnUserPreConsented(oldPackage)) {
201 // Currently prepared VPN is revoked, so unprepare it and return false.
202 prepareInternal(VpnConfig.LEGACY_VPN);
203 return false;
Jeff Davidson05542602014-08-11 14:07:27 -0700204 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700205 }
206
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700207 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700208 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
209 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700210 return true;
211 }
212
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700213 // Check if the caller is authorized.
214 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700215
Jeff Davidson11008a72014-11-20 13:12:46 -0800216 prepareInternal(newPackage);
217 return true;
218 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700219
Jeff Davidson11008a72014-11-20 13:12:46 -0800220 /** Prepare the VPN for the given package. Does not perform permission checks. */
221 private void prepareInternal(String newPackage) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400222 long token = Binder.clearCallingIdentity();
223 try {
Jeff Davidson11008a72014-11-20 13:12:46 -0800224 // Reset the interface.
225 if (mInterface != null) {
226 mStatusIntent = null;
227 agentDisconnect();
228 jniReset(mInterface);
229 mInterface = null;
230 mVpnUsers = null;
231 }
232
233 // Revoke the connection or stop LegacyVpnRunner.
234 if (mConnection != null) {
235 try {
236 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
237 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
238 } catch (Exception e) {
239 // ignore
240 }
241 mContext.unbindService(mConnection);
242 mConnection = null;
243 } else if (mLegacyVpnRunner != null) {
244 mLegacyVpnRunner.exit();
245 mLegacyVpnRunner = null;
246 }
247
248 try {
249 mNetd.denyProtect(mOwnerUID);
250 } catch (Exception e) {
251 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
252 }
253
254 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
255 mPackage = newPackage;
256 mOwnerUID = getAppUid(newPackage, mUserHandle);
257 try {
258 mNetd.allowProtect(mOwnerUID);
259 } catch (Exception e) {
260 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
261 }
262 mConfig = null;
263
264 updateState(DetailedState.IDLE, "prepare");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400265 } finally {
266 Binder.restoreCallingIdentity(token);
267 }
Chia-chi Yehe9107902011-07-02 01:48:50 -0700268 }
269
Jeff Davidson05542602014-08-11 14:07:27 -0700270 /**
Robin Lee3b3dd942015-05-12 18:14:58 +0100271 * Set whether a package has the ability to launch VPNs without user intervention.
Jeff Davidson05542602014-08-11 14:07:27 -0700272 */
Robin Lee3b3dd942015-05-12 18:14:58 +0100273 public void setPackageAuthorization(String packageName, boolean authorized) {
Jeff Davidson05542602014-08-11 14:07:27 -0700274 // Check if the caller is authorized.
275 enforceControlPermission();
276
Robin Lee3b3dd942015-05-12 18:14:58 +0100277 int uid = getAppUid(packageName, mUserHandle);
278 if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
279 // Authorization for nonexistent packages (or fake ones) can't be updated.
Jeff Davidson05542602014-08-11 14:07:27 -0700280 return;
281 }
282
283 long token = Binder.clearCallingIdentity();
284 try {
285 AppOpsManager appOps =
286 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Robin Lee3b3dd942015-05-12 18:14:58 +0100287 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
Jeff Davidson05542602014-08-11 14:07:27 -0700288 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
289 } catch (Exception e) {
Robin Lee3b3dd942015-05-12 18:14:58 +0100290 Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
Jeff Davidson05542602014-08-11 14:07:27 -0700291 } finally {
292 Binder.restoreCallingIdentity(token);
293 }
294 }
295
296 private boolean isVpnUserPreConsented(String packageName) {
297 AppOpsManager appOps =
298 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
299
300 // Verify that the caller matches the given package and has permission to activate VPNs.
301 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
302 packageName) == AppOpsManager.MODE_ALLOWED;
303 }
304
Paul Jensen0784eea2014-08-19 16:00:24 -0400305 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700306 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400307 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700308 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400309 PackageManager pm = mContext.getPackageManager();
310 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700311 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700312 result = pm.getPackageUidAsUser(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400313 } catch (NameNotFoundException e) {
314 result = -1;
315 }
316 return result;
317 }
318
319 public NetworkInfo getNetworkInfo() {
320 return mNetworkInfo;
321 }
322
Paul Jensen31a94f42015-02-13 14:18:39 -0500323 public int getNetId() {
324 return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
325 }
326
Lorenzo Colitti60446162014-09-20 00:14:31 +0900327 private LinkProperties makeLinkProperties() {
328 boolean allowIPv4 = mConfig.allowIPv4;
329 boolean allowIPv6 = mConfig.allowIPv6;
330
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400331 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900332
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400333 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700334
Lorenzo Colitti60446162014-09-20 00:14:31 +0900335 if (mConfig.addresses != null) {
336 for (LinkAddress address : mConfig.addresses) {
337 lp.addLinkAddress(address);
338 allowIPv4 |= address.getAddress() instanceof Inet4Address;
339 allowIPv6 |= address.getAddress() instanceof Inet6Address;
340 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400341 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900342
343 if (mConfig.routes != null) {
344 for (RouteInfo route : mConfig.routes) {
345 lp.addRoute(route);
346 InetAddress address = route.getDestination().getAddress();
347 allowIPv4 |= address instanceof Inet4Address;
348 allowIPv6 |= address instanceof Inet6Address;
349 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400350 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700351
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400352 if (mConfig.dnsServers != null) {
353 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700354 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
355 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900356 allowIPv4 |= address instanceof Inet4Address;
357 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400358 }
359 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700360
Lorenzo Colitti60446162014-09-20 00:14:31 +0900361 if (!allowIPv4) {
362 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
363 }
364 if (!allowIPv6) {
365 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
366 }
367
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400368 // Concatenate search domains into a string.
369 StringBuilder buffer = new StringBuilder();
370 if (mConfig.searchDomains != null) {
371 for (String domain : mConfig.searchDomains) {
372 buffer.append(domain).append(' ');
373 }
374 }
375 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700376
Lorenzo Colitti60446162014-09-20 00:14:31 +0900377 // TODO: Stop setting the MTU in jniCreate and set it here.
378
379 return lp;
380 }
381
382 private void agentConnect() {
383 LinkProperties lp = makeLinkProperties();
384
385 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
386 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
387 } else {
388 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
389 }
390
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400391 mNetworkInfo.setIsAvailable(true);
392 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700393
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700394 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700395 networkMisc.allowBypass = mConfig.allowBypass;
396
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400397 long token = Binder.clearCallingIdentity();
398 try {
399 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700400 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700401 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400402 public void unwanted() {
403 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700404 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400405 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700406 } finally {
407 Binder.restoreCallingIdentity(token);
408 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700409
Paul Jensen0784eea2014-08-19 16:00:24 -0400410 addVpnUserLocked(mUserHandle);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700411 // If the user can have restricted profiles, assign all its restricted profiles to this VPN
412 if (canHaveRestrictedProfile(mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400413 token = Binder.clearCallingIdentity();
414 List<UserInfo> users;
415 try {
416 users = UserManager.get(mContext).getUsers();
417 } finally {
418 Binder.restoreCallingIdentity(token);
419 }
420 for (UserInfo user : users) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700421 if (user.isRestricted() && (user.restrictedProfileParentId == mUserHandle)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400422 addVpnUserLocked(user.id);
423 }
424 }
425 }
426 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
427 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700428
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700429 private boolean canHaveRestrictedProfile(int userId) {
430 long token = Binder.clearCallingIdentity();
431 try {
432 return UserManager.get(mContext).canHaveRestrictedProfile(userId);
433 } finally {
434 Binder.restoreCallingIdentity(token);
435 }
436 }
437
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400438 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
439 networkInfo.setIsAvailable(false);
440 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
441 if (networkAgent != null) {
442 networkAgent.sendNetworkInfo(networkInfo);
443 }
444 }
445
446 private void agentDisconnect(NetworkAgent networkAgent) {
447 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
448 agentDisconnect(networkInfo, networkAgent);
449 }
450
451 private void agentDisconnect() {
452 if (mNetworkInfo.isConnected()) {
453 agentDisconnect(mNetworkInfo, mNetworkAgent);
454 mNetworkAgent = null;
455 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700456 }
457
458 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700459 * Establish a VPN network and return the file descriptor of the VPN
460 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700461 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700462 *
463 * @param config The parameters to configure the network.
464 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700465 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700466 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700467 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700468 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400469 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700470 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700471 }
Jeff Davidson0a775ce2015-04-27 15:02:48 -0700472 // Check to ensure consent hasn't been revoked since we were prepared.
473 if (!isVpnUserPreConsented(mPackage)) {
474 return null;
475 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700476 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700477 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
478 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700479 long token = Binder.clearCallingIdentity();
480 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700481 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400482 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000483 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
484 new UserHandle(mUserHandle))) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700485 throw new SecurityException("Restricted users cannot establish VPNs");
486 }
487
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700488 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400489 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700490 if (info == null) {
491 throw new SecurityException("Cannot find " + config.user);
492 }
493 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
494 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
495 }
496 } catch (RemoteException e) {
497 throw new SecurityException("Cannot find " + config.user);
498 } finally {
499 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700500 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700501
Chad Brubaker850eb672014-03-21 21:02:47 +0000502 // Save the old config in case we need to go back.
503 VpnConfig oldConfig = mConfig;
504 String oldInterface = mInterface;
505 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400506 NetworkAgent oldNetworkAgent = mNetworkAgent;
507 mNetworkAgent = null;
508 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000509
Chia-chi Yehe9107902011-07-02 01:48:50 -0700510 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700511 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700512 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700513 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700514 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700515
Chad Brubakerc2865192013-07-10 14:46:23 -0700516 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700517 StringBuilder builder = new StringBuilder();
518 for (LinkAddress address : config.addresses) {
519 builder.append(" " + address);
520 }
521 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700522 throw new IllegalArgumentException("At least one address must be specified");
523 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700524 Connection connection = new Connection();
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700525 if (!mContext.bindServiceAsUser(intent, connection,
526 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
527 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700528 throw new IllegalStateException("Cannot bind " + config.user);
529 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000530
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700531 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700532 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700533
534 // Fill more values.
535 config.user = mPackage;
536 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700537 config.startTime = SystemClock.elapsedRealtime();
538 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000539
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700540 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400541 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700542
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400543 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000544
545 if (oldConnection != null) {
546 mContext.unbindService(oldConnection);
547 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400548 // Remove the old tun's user forwarding rules
549 // The new tun's user rules have already been added so they will take over
550 // as rules are deleted. This prevents data leakage as the rules are moved over.
551 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000552 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000553 jniReset(oldInterface);
554 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700555
556 try {
557 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
558 } catch (IOException e) {
559 throw new IllegalStateException(
560 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
561 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000562 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000563 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400564 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000565 // restore old state
566 mConfig = oldConfig;
567 mConnection = oldConnection;
568 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400569 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000570 mInterface = oldInterface;
571 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700572 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000573 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700574 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700575 }
576
Chad Brubakerc2865192013-07-10 14:46:23 -0700577 private boolean isRunningLocked() {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800578 return mNetworkAgent != null && mInterface != null;
579 }
580
581 // Returns true if the VPN has been established and the calling UID is its owner. Used to check
582 // that a call to mutate VPN state is admissible.
583 private boolean isCallerEstablishedOwnerLocked() {
584 return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
Chad Brubakerc2865192013-07-10 14:46:23 -0700585 }
586
Paul Jensen0784eea2014-08-19 16:00:24 -0400587 // Note: Return type guarantees results are deduped and sorted, which callers require.
588 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
589 SortedSet<Integer> uids = new TreeSet<Integer>();
590 for (String app : packageNames) {
591 int uid = getAppUid(app, userHandle);
592 if (uid != -1) uids.add(uid);
593 }
594 return uids;
595 }
596
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400597 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400598 private void addVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800599 if (mVpnUsers == null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700600 throw new IllegalStateException("VPN is not active");
601 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700602
Paul Jensen0784eea2014-08-19 16:00:24 -0400603 if (mConfig.allowedApplications != null) {
604 // Add ranges covering all UIDs for allowedApplications.
605 int start = -1, stop = -1;
606 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
607 if (start == -1) {
608 start = uid;
609 } else if (uid != stop + 1) {
610 mVpnUsers.add(new UidRange(start, stop));
611 start = uid;
612 }
613 stop = uid;
614 }
615 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
616 } else if (mConfig.disallowedApplications != null) {
617 // Add all ranges for user skipping UIDs for disallowedApplications.
618 final UidRange userRange = UidRange.createForUser(userHandle);
619 int start = userRange.start;
620 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
621 if (uid == start) {
622 start++;
623 } else {
624 mVpnUsers.add(new UidRange(start, uid - 1));
625 start = uid + 1;
626 }
627 }
628 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
629 } else {
630 // Add all UIDs for the user.
631 mVpnUsers.add(UidRange.createForUser(userHandle));
632 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700633
634 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700635 }
636
Paul Jensen0784eea2014-08-19 16:00:24 -0400637 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
638 // apply to userHandle.
639 private List<UidRange> uidRangesForUser(int userHandle) {
640 final UidRange userRange = UidRange.createForUser(userHandle);
641 final List<UidRange> ranges = new ArrayList<UidRange>();
642 for (UidRange range : mVpnUsers) {
643 if (range.start >= userRange.start && range.stop <= userRange.stop) {
644 ranges.add(range);
645 }
646 }
647 return ranges;
648 }
649
650 private void removeVpnUserLocked(int userHandle) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800651 if (mVpnUsers == null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700652 throw new IllegalStateException("VPN is not active");
653 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400654 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700655 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400656 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700657 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400658 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700659 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700660 }
661
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700662 public void onUserAdded(int userHandle) {
663 // If the user is restricted tie them to the parent user's VPN
664 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
665 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
666 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700667 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400668 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400669 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400670 final List<UidRange> ranges = uidRangesForUser(userHandle);
671 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400672 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700673 } catch (Exception e) {
674 Log.wtf(TAG, "Failed to add restricted user to owner", e);
675 }
676 }
677 }
678 }
679
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700680 public void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700681 // clean up if restricted
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700682 UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
683 if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
684 synchronized(Vpn.this) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700685 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400686 removeVpnUserLocked(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700687 } catch (Exception e) {
688 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
689 }
690 }
691 }
692 }
693
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700694 /**
695 * Return the configuration of the currently running VPN.
696 */
697 public VpnConfig getVpnConfig() {
698 enforceControlPermission();
699 return mConfig;
700 }
701
Jeff Sharkey899223b2012-08-04 15:24:58 -0700702 @Deprecated
703 public synchronized void interfaceStatusChanged(String iface, boolean up) {
704 try {
705 mObserver.interfaceStatusChanged(iface, up);
706 } catch (RemoteException e) {
707 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700708 }
709 }
710
Jeff Sharkey899223b2012-08-04 15:24:58 -0700711 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
712 @Override
713 public void interfaceStatusChanged(String interfaze, boolean up) {
714 synchronized (Vpn.this) {
715 if (!up && mLegacyVpnRunner != null) {
716 mLegacyVpnRunner.check(interfaze);
717 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700718 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700719 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700720
Jeff Sharkey899223b2012-08-04 15:24:58 -0700721 @Override
722 public void interfaceRemoved(String interfaze) {
723 synchronized (Vpn.this) {
724 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700725 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400726 mVpnUsers = null;
Paul Jensenc4c72312014-12-08 14:04:51 -0500727 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 mInterface = null;
729 if (mConnection != null) {
730 mContext.unbindService(mConnection);
731 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400732 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700733 } else if (mLegacyVpnRunner != null) {
734 mLegacyVpnRunner.exit();
735 mLegacyVpnRunner = null;
736 }
737 }
738 }
739 }
740 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700741
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700742 private void enforceControlPermission() {
Jeff Davidsonbc19c182014-11-11 13:20:01 -0800743 mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700744 }
745
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700746 private class Connection implements ServiceConnection {
747 private IBinder mService;
748
749 @Override
750 public void onServiceConnected(ComponentName name, IBinder service) {
751 mService = service;
752 }
753
754 @Override
755 public void onServiceDisconnected(ComponentName name) {
756 mService = null;
757 }
758 }
759
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700760 private void prepareStatusIntent() {
761 final long token = Binder.clearCallingIdentity();
762 try {
763 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
764 } finally {
765 Binder.restoreCallingIdentity(token);
766 }
767 }
768
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700769 public synchronized boolean addAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800770 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700771 return false;
772 }
773 boolean success = jniAddAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800774 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700775 return success;
776 }
777
778 public synchronized boolean removeAddress(String address, int prefixLength) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800779 if (!isCallerEstablishedOwnerLocked()) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700780 return false;
781 }
782 boolean success = jniDelAddress(mInterface, address, prefixLength);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800783 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700784 return success;
785 }
786
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800787 public synchronized boolean setUnderlyingNetworks(Network[] networks) {
788 if (!isCallerEstablishedOwnerLocked()) {
789 return false;
790 }
791 if (networks == null) {
792 mConfig.underlyingNetworks = null;
793 } else {
794 mConfig.underlyingNetworks = new Network[networks.length];
795 for (int i = 0; i < networks.length; ++i) {
796 if (networks[i] == null) {
797 mConfig.underlyingNetworks[i] = null;
798 } else {
799 mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
800 }
801 }
802 }
803 return true;
804 }
805
806 public synchronized Network[] getUnderlyingNetworks() {
807 if (!isRunningLocked()) {
808 return null;
809 }
810 return mConfig.underlyingNetworks;
811 }
812
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800813 /**
814 * This method should only be called by ConnectivityService. Because it doesn't
815 * have enough data to fill VpnInfo.primaryUnderlyingIface field.
816 */
817 public synchronized VpnInfo getVpnInfo() {
818 if (!isRunningLocked()) {
819 return null;
820 }
821
822 VpnInfo info = new VpnInfo();
823 info.ownerUid = mOwnerUID;
824 info.vpnIface = mInterface;
825 return info;
826 }
827
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800828 public synchronized boolean appliesToUid(int uid) {
829 if (!isRunningLocked()) {
830 return false;
831 }
832 for (UidRange uidRange : mVpnUsers) {
833 if (uidRange.start <= uid && uid <= uidRange.stop) {
834 return true;
835 }
836 }
837 return false;
838 }
839
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700840 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700841 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700842 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700843 private native void jniReset(String interfaze);
844 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700845 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
846 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700847
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900848 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
849 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700850 // Currently legacy VPN only works on IPv4.
851 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900852 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700853 }
854 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700855
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900856 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700857 }
858
859 /**
860 * Start legacy VPN, controlling native daemons as needed. Creates a
861 * secondary thread to perform connection work, returning quickly.
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800862 *
863 * Should only be called to respond to Binder requests as this enforces caller permission. Use
864 * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
865 * permission check only when the caller is trusted (or the call is initiated by the system).
Jeff Sharkey82f85212012-08-24 11:17:25 -0700866 */
867 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800868 enforceControlPermission();
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800869 long token = Binder.clearCallingIdentity();
870 try {
871 startLegacyVpnPrivileged(profile, keyStore, egress);
872 } finally {
873 Binder.restoreCallingIdentity(token);
874 }
875 }
876
877 /**
878 * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
879 * permissions under the assumption that the caller is the system.
880 *
881 * Callers are responsible for checking permissions if needed.
882 */
883 public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
884 LinkProperties egress) {
Kenny Rootb9594ce2013-02-14 10:18:38 -0800885 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700886 throw new IllegalStateException("KeyStore isn't unlocked");
887 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400888 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400889 UserInfo user = mgr.getUserInfo(mUserHandle);
Nicolas Prevot95778ff2015-01-06 15:43:05 +0000890 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
891 new UserHandle(mUserHandle))) {
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400892 throw new SecurityException("Restricted users cannot establish VPNs");
893 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700894
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900895 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
896 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
897 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700898
899 // Load certificates.
900 String privateKey = "";
901 String userCert = "";
902 String caCert = "";
903 String serverCert = "";
904 if (!profile.ipsecUserCert.isEmpty()) {
905 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
906 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700907 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700908 }
909 if (!profile.ipsecCaCert.isEmpty()) {
910 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700911 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700912 }
913 if (!profile.ipsecServerCert.isEmpty()) {
914 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700915 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700916 }
917 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
918 throw new IllegalStateException("Cannot load credentials");
919 }
920
921 // Prepare arguments for racoon.
922 String[] racoon = null;
923 switch (profile.type) {
924 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
925 racoon = new String[] {
926 iface, profile.server, "udppsk", profile.ipsecIdentifier,
927 profile.ipsecSecret, "1701",
928 };
929 break;
930 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
931 racoon = new String[] {
932 iface, profile.server, "udprsa", privateKey, userCert,
933 caCert, serverCert, "1701",
934 };
935 break;
936 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
937 racoon = new String[] {
938 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
939 profile.ipsecSecret, profile.username, profile.password, "", gateway,
940 };
941 break;
942 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
943 racoon = new String[] {
944 iface, profile.server, "xauthrsa", privateKey, userCert,
945 caCert, serverCert, profile.username, profile.password, "", gateway,
946 };
947 break;
948 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
949 racoon = new String[] {
950 iface, profile.server, "hybridrsa",
951 caCert, serverCert, profile.username, profile.password, "", gateway,
952 };
953 break;
954 }
955
956 // Prepare arguments for mtpd.
957 String[] mtpd = null;
958 switch (profile.type) {
959 case VpnProfile.TYPE_PPTP:
960 mtpd = new String[] {
961 iface, "pptp", profile.server, "1723",
962 "name", profile.username, "password", profile.password,
963 "linkname", "vpn", "refuse-eap", "nodefaultroute",
964 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
965 (profile.mppe ? "+mppe" : "nomppe"),
966 };
967 break;
968 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
969 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
970 mtpd = new String[] {
971 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
972 "name", profile.username, "password", profile.password,
973 "linkname", "vpn", "refuse-eap", "nodefaultroute",
974 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
975 };
976 break;
977 }
978
979 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700980 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700981 config.user = profile.key;
982 config.interfaze = iface;
983 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700984
985 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700986 if (!profile.dnsServers.isEmpty()) {
987 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
988 }
989 if (!profile.searchDomains.isEmpty()) {
990 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
991 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700992 startLegacyVpn(config, racoon, mtpd);
993 }
994
995 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800996 stopLegacyVpnPrivileged();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700997
Jeff Davidsonb21298a2015-02-10 10:02:11 -0800998 // Prepare for the new request.
999 prepareInternal(VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -07001000 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001001
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001002 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -07001003 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1004 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001005 }
1006
Jeff Davidsonb21298a2015-02-10 10:02:11 -08001007 /** Stop legacy VPN. Permissions must be checked by callers. */
1008 public synchronized void stopLegacyVpnPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001009 if (mLegacyVpnRunner != null) {
1010 mLegacyVpnRunner.exit();
1011 mLegacyVpnRunner = null;
1012
1013 synchronized (LegacyVpnRunner.TAG) {
1014 // wait for old thread to completely finish before spinning up
1015 // new instance, otherwise state updates can be out of order.
1016 }
1017 }
1018 }
1019
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001020 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001021 * Return the information of the current ongoing legacy VPN.
1022 */
1023 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -07001024 // Check if the caller is authorized.
1025 enforceControlPermission();
sj.cha08bbca02015-03-23 11:35:24 +09001026 return getLegacyVpnInfoPrivileged();
1027 }
1028
1029 /**
1030 * Return the information of the current ongoing legacy VPN.
1031 * Callers are responsible for checking permissions if needed.
1032 */
1033 public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001034 if (mLegacyVpnRunner == null) return null;
1035
1036 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -07001037 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -07001038 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -07001039 if (mNetworkInfo.isConnected()) {
1040 info.intent = mStatusIntent;
1041 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001042 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001043 }
1044
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001045 public VpnConfig getLegacyVpnConfig() {
1046 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -07001047 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001048 } else {
1049 return null;
1050 }
1051 }
1052
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001053 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001054 * Bringing up a VPN connection takes time, and that is all this thread
1055 * does. Here we have plenty of time. The only thing we need to take
1056 * care of is responding to interruptions as soon as possible. Otherwise
1057 * requests will be piled up. This can be done in a Handler as a state
1058 * machine, but it is much easier to read in the current form.
1059 */
1060 private class LegacyVpnRunner extends Thread {
1061 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001063 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001064 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001065 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001066 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001067 private final AtomicInteger mOuterConnection =
1068 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001069
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001070 private long mTimer = -1;
1071
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001072 /**
1073 * Watch for the outer connection (passing in the constructor) going away.
1074 */
1075 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1076 @Override
1077 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001078 if (!mEnableTeardown) return;
1079
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001080 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1081 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1082 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1083 NetworkInfo info = (NetworkInfo)intent.getExtra(
1084 ConnectivityManager.EXTRA_NETWORK_INFO);
1085 if (info != null && !info.isConnectedOrConnecting()) {
1086 try {
1087 mObserver.interfaceStatusChanged(mOuterInterface, false);
1088 } catch (RemoteException e) {}
1089 }
1090 }
1091 }
1092 }
1093 };
1094
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001095 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001096 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001097 mConfig = config;
1098 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001099 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001100 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001101 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001102
1103 // This is the interface which VPN is running on,
1104 // mConfig.interfaze will change to point to OUR
1105 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001106 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001107 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001108 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001109 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001110
Paul Jensene75b9e32015-04-06 11:54:53 -04001111 if (!TextUtils.isEmpty(mOuterInterface)) {
1112 final ConnectivityManager cm = ConnectivityManager.from(mContext);
1113 for (Network network : cm.getAllNetworks()) {
1114 final LinkProperties lp = cm.getLinkProperties(network);
Lorenzo Colitti1b60d112015-07-02 13:03:03 +09001115 if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001116 final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1117 if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1118 }
1119 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001120 }
1121
1122 IntentFilter filter = new IntentFilter();
1123 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1124 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001125 }
1126
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001127 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001128 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001129 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1130 exit();
1131 }
1132 }
1133
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001134 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001135 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001136 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001137 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001138 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001139 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001140 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001141 try {
1142 mContext.unregisterReceiver(mBroadcastReceiver);
1143 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001144 }
1145
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146 @Override
1147 public void run() {
1148 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001149 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001150 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001151 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001152 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001153 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001154 }
1155 }
1156
1157 private void checkpoint(boolean yield) throws InterruptedException {
1158 long now = SystemClock.elapsedRealtime();
1159 if (mTimer == -1) {
1160 mTimer = now;
1161 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001162 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001163 Thread.sleep(yield ? 200 : 1);
1164 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001165 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001166 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001167 }
1168 }
1169
1170 private void execute() {
1171 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001172 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001173 try {
1174 // Initialize the timer.
1175 checkpoint(false);
1176
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001177 // Wait for the daemons to stop.
1178 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001179 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001180 checkpoint(true);
1181 }
1182 }
1183
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001184 // Clear the previous state.
1185 File state = new File("/data/misc/vpn/state");
1186 state.delete();
1187 if (state.exists()) {
1188 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001189 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001190 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001191 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001192
Chia-chi Yehe9107902011-07-02 01:48:50 -07001193 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001194 boolean restart = false;
1195 for (String[] arguments : mArguments) {
1196 restart = restart || (arguments != null);
1197 }
1198 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001199 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001200 return;
1201 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001202 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001203
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001204 // Start the daemon with arguments.
1205 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001206 String[] arguments = mArguments[i];
1207 if (arguments == null) {
1208 continue;
1209 }
1210
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001211 // Start the daemon.
1212 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001213 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001214
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001215 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001216 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001217 checkpoint(true);
1218 }
1219
1220 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001221 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001222 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001223 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001224
1225 // Wait for the socket to connect.
1226 while (true) {
1227 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001228 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001229 break;
1230 } catch (Exception e) {
1231 // ignore
1232 }
1233 checkpoint(true);
1234 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001235 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001236
1237 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001238 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001239 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001240 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001241 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001242 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001243 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001244 out.write(bytes.length >> 8);
1245 out.write(bytes.length);
1246 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001247 checkpoint(false);
1248 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001249 out.write(0xFF);
1250 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001251 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001252
1253 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001254 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001255 while (true) {
1256 try {
1257 if (in.read() == -1) {
1258 break;
1259 }
1260 } catch (Exception e) {
1261 // ignore
1262 }
1263 checkpoint(true);
1264 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001265 }
1266
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001267 // Wait for the daemons to create the new state.
1268 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001269 // Check if a running daemon is dead.
1270 for (int i = 0; i < mDaemons.length; ++i) {
1271 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001272 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001273 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001274 }
1275 }
1276 checkpoint(true);
1277 }
1278
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001279 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001280 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001281 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001282 throw new IllegalStateException("Cannot parse the state");
1283 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001284
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001285 // Set the interface and the addresses in the config.
1286 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001287
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001288 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001289 // Set the routes if they are not set in the config.
1290 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001291 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001292 }
1293
1294 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001295 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001296 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001297 if (!dnsServers.isEmpty()) {
1298 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1299 }
1300 }
1301
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001302 // Set the search domains if they are not set in the config.
1303 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1304 String searchDomains = parameters[4].trim();
1305 if (!searchDomains.isEmpty()) {
1306 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1307 }
1308 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001309
Lorenzo Colitti50262792014-09-19 01:53:35 +09001310 // Add a throw route for the VPN server endpoint, if one was specified.
1311 String endpoint = parameters[5];
1312 if (!endpoint.isEmpty()) {
1313 try {
1314 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1315 if (addr instanceof Inet4Address) {
1316 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1317 } else if (addr instanceof Inet6Address) {
1318 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1319 } else {
1320 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1321 }
1322 } catch (IllegalArgumentException e) {
1323 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1324 }
1325 }
1326
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001327 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001328 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001329 // Set the start time
1330 mConfig.startTime = SystemClock.elapsedRealtime();
1331
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001332 // Check if the thread is interrupted while we are waiting.
1333 checkpoint(false);
1334
Chia-chi Yehe9107902011-07-02 01:48:50 -07001335 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001336 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001337 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001338 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001339
1340 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001341 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001342 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001343
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001344 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001345
1346 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001347 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001348 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001349 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001350 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001351 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001352 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001353 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001354 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001355 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001356 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001357 }
1358 }
1359
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001360 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001361 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001362 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001363 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001364 }
1365 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001366
1367 /**
1368 * Monitor the daemons we started, moving to disconnected state if the
1369 * underlying services fail.
1370 */
1371 private void monitorDaemons() {
1372 if (!mNetworkInfo.isConnected()) {
1373 return;
1374 }
1375
1376 try {
1377 while (true) {
1378 Thread.sleep(2000);
1379 for (int i = 0; i < mDaemons.length; i++) {
1380 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1381 return;
1382 }
1383 }
1384 }
1385 } catch (InterruptedException e) {
1386 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1387 } finally {
1388 for (String daemon : mDaemons) {
1389 SystemService.stop(daemon);
1390 }
1391
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001392 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001393 }
1394 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001395 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001396}