blob: 83756aa8cd0693cf76ecfc0565b4ea42362e87c0 [file] [log] [blame]
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Jeff Sharkey899223b2012-08-04 15:24:58 -070019import static android.Manifest.permission.BIND_VPN_SERVICE;
Paul Jensen0784eea2014-08-19 16:00:24 -040020import static android.os.UserHandle.PER_USER_RANGE;
Lorenzo Colitti50262792014-09-19 01:53:35 +090021import static android.net.RouteInfo.RTN_THROW;
Lorenzo Colitti60446162014-09-20 00:14:31 +090022import static android.net.RouteInfo.RTN_UNREACHABLE;
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -070023import static android.system.OsConstants.AF_INET;
24import static android.system.OsConstants.AF_INET6;
Jeff Sharkey899223b2012-08-04 15:24:58 -070025
Chad Brubaker4ca19e82013-06-14 11:16:51 -070026import android.app.AppGlobals;
Jeff Davidson05542602014-08-11 14:07:27 -070027import android.app.AppOpsManager;
Jeff Davidson90b1b9f2014-08-22 13:05:43 -070028import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070029import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070031import android.content.Context;
32import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070033import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070035import android.content.pm.ApplicationInfo;
36import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040037import android.content.pm.PackageManager.NameNotFoundException;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070038import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070039import android.content.pm.UserInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070040import android.net.ConnectivityManager;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070041import android.net.IConnectivityManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070042import android.net.INetworkManagementEventObserver;
Lorenzo Colitti50262792014-09-19 01:53:35 +090043import android.net.IpPrefix;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070044import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070045import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070046import android.net.LocalSocket;
47import android.net.LocalSocketAddress;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040048import android.net.NetworkAgent;
49import android.net.NetworkCapabilities;
Jeff Sharkey899223b2012-08-04 15:24:58 -070050import android.net.NetworkInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040051import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070052import android.net.NetworkMisc;
Jeff Sharkey82f85212012-08-24 11:17:25 -070053import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040054import android.net.UidRange;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070055import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080056import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070057import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070058import android.os.INetworkManagementService;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040059import android.os.Looper;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070060import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070061import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070062import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070063import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070064import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070065import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070066import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070067import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070068import android.security.Credentials;
69import android.security.KeyStore;
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;
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;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700115 private final IConnectivityManager mConnService;
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 private BroadcastReceiver mUserIntentReceiver = null;
126
Paul Jensen0784eea2014-08-19 16:00:24 -0400127 // Handle of user initiating VPN.
128 private final int mUserHandle;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700129
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400130 public Vpn(Looper looper, Context context, INetworkManagementService netService,
Paul Jensen0784eea2014-08-19 16:00:24 -0400131 IConnectivityManager connService, int userHandle) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700132 mContext = context;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400133 mNetd = netService;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700134 mConnService = connService;
Paul Jensen0784eea2014-08-19 16:00:24 -0400135 mUserHandle = userHandle;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400136 mLooper = looper;
137
138 mPackage = VpnConfig.LEGACY_VPN;
Paul Jensen0784eea2014-08-19 16:00:24 -0400139 mOwnerUID = getAppUid(mPackage, mUserHandle);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700140
141 try {
142 netService.registerObserver(mObserver);
143 } catch (RemoteException e) {
144 Log.wtf(TAG, "Problem registering observer", e);
145 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400146 if (userHandle == UserHandle.USER_OWNER) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700147 // Owner's VPN also needs to handle restricted users
148 mUserIntentReceiver = new BroadcastReceiver() {
149 @Override
150 public void onReceive(Context context, Intent intent) {
151 final String action = intent.getAction();
Paul Jensen0784eea2014-08-19 16:00:24 -0400152 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Chad Brubakerc2865192013-07-10 14:46:23 -0700153 UserHandle.USER_NULL);
Paul Jensen0784eea2014-08-19 16:00:24 -0400154 if (userHandle == UserHandle.USER_NULL) return;
Chad Brubakerc2865192013-07-10 14:46:23 -0700155
156 if (Intent.ACTION_USER_ADDED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400157 onUserAdded(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700158 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400159 onUserRemoved(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700160 }
161 }
162 };
163
164 IntentFilter intentFilter = new IntentFilter();
165 intentFilter.addAction(Intent.ACTION_USER_ADDED);
166 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
167 mContext.registerReceiverAsUser(
168 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
169 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400170
171 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
172 // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
173 mNetworkCapabilities = new NetworkCapabilities();
174 mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
175 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700176 }
177
Jeff Sharkey57666932013-04-30 17:01:57 -0700178 /**
Jeff Sharkey57666932013-04-30 17:01:57 -0700179 * Set if this object is responsible for watching for {@link NetworkInfo}
180 * teardown. When {@code false}, teardown is handled externally by someone
181 * else.
182 */
183 public void setEnableTeardown(boolean enableTeardown) {
184 mEnableTeardown = enableTeardown;
185 }
186
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 /**
188 * Update current state, dispaching event to listeners.
189 */
190 private void updateState(DetailedState detailedState, String reason) {
191 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
192 mNetworkInfo.setDetailedState(detailedState, reason, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400193 if (mNetworkAgent != null) {
194 mNetworkAgent.sendNetworkInfo(mNetworkInfo);
195 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700196 }
197
198 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700199 * Prepare for a VPN application. This method is designed to solve
200 * race conditions. It first compares the current prepared package
201 * with {@code oldPackage}. If they are the same, the prepared
202 * package is revoked and replaced with {@code newPackage}. If
203 * {@code oldPackage} is {@code null}, the comparison is omitted.
204 * If {@code newPackage} is the same package or {@code null}, the
205 * revocation is omitted. This method returns {@code true} if the
206 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700208 * Legacy VPN is handled specially since it is not a real package.
209 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
210 * it can be revoked by itself.
211 *
212 * @param oldPackage The package name of the old VPN application.
213 * @param newPackage The package name of the new VPN application.
214 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700215 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700216 public synchronized boolean prepare(String oldPackage, String newPackage) {
217 // Return false if the package does not match.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700218 if (oldPackage != null && getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
Jeff Davidson05542602014-08-11 14:07:27 -0700219 // The package doesn't match. If this VPN was not previously authorized, return false
220 // to force user authorization. Otherwise, revoke the VPN anyway.
221 if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
222 long token = Binder.clearCallingIdentity();
223 try {
224 // This looks bizarre, but it is what ConfirmDialog in VpnDialogs is doing when
225 // the user clicks through to allow the VPN to consent. So we are emulating the
226 // action of the dialog without actually showing it.
227 prepare(null, oldPackage);
228 } finally {
229 Binder.restoreCallingIdentity(token);
230 }
231 return true;
232 }
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700233 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700234 }
235
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700236 // Return true if we do not need to revoke.
Jeff Davidsonbe085872014-10-24 10:35:53 -0700237 if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
238 getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700239 return true;
240 }
241
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700242 // Check if the caller is authorized.
243 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700244
Jeff Davidson05542602014-08-11 14:07:27 -0700245 // Reset the interface.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700246 if (mInterface != null) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700247 mStatusIntent = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400248 agentDisconnect();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700249 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700250 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700251 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700252 }
253
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700254 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700255 if (mConnection != null) {
256 try {
257 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
258 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
259 } catch (Exception e) {
260 // ignore
261 }
262 mContext.unbindService(mConnection);
263 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700264 } else if (mLegacyVpnRunner != null) {
265 mLegacyVpnRunner.exit();
266 mLegacyVpnRunner = null;
267 }
268
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400269 long token = Binder.clearCallingIdentity();
270 try {
271 mNetd.denyProtect(mOwnerUID);
272 } catch (Exception e) {
273 Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
274 } finally {
275 Binder.restoreCallingIdentity(token);
276 }
277
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700278 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
279 mPackage = newPackage;
Paul Jensen0784eea2014-08-19 16:00:24 -0400280 mOwnerUID = getAppUid(newPackage, mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400281 token = Binder.clearCallingIdentity();
282 try {
283 mNetd.allowProtect(mOwnerUID);
284 } catch (Exception e) {
285 Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
286 } finally {
287 Binder.restoreCallingIdentity(token);
288 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700289 mConfig = null;
Jeff Davidson05542602014-08-11 14:07:27 -0700290
Jeff Sharkey899223b2012-08-04 15:24:58 -0700291 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700292 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700293 }
294
Jeff Davidson05542602014-08-11 14:07:27 -0700295 /**
296 * Set whether the current package has the ability to launch VPNs without user intervention.
297 */
298 public void setPackageAuthorization(boolean authorized) {
299 // Check if the caller is authorized.
300 enforceControlPermission();
301
302 if (mPackage == null || VpnConfig.LEGACY_VPN.equals(mPackage)) {
303 return;
304 }
305
306 long token = Binder.clearCallingIdentity();
307 try {
308 AppOpsManager appOps =
309 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
310 appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, mOwnerUID, mPackage,
311 authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
312 } catch (Exception e) {
313 Log.wtf(TAG, "Failed to set app ops for package " + mPackage, e);
314 } finally {
315 Binder.restoreCallingIdentity(token);
316 }
317 }
318
319 private boolean isVpnUserPreConsented(String packageName) {
320 AppOpsManager appOps =
321 (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
322
323 // Verify that the caller matches the given package and has permission to activate VPNs.
324 return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
325 packageName) == AppOpsManager.MODE_ALLOWED;
326 }
327
Paul Jensen0784eea2014-08-19 16:00:24 -0400328 private int getAppUid(String app, int userHandle) {
Jeff Davidson05542602014-08-11 14:07:27 -0700329 if (VpnConfig.LEGACY_VPN.equals(app)) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400330 return Process.myUid();
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700331 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400332 PackageManager pm = mContext.getPackageManager();
333 int result;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700334 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400335 result = pm.getPackageUid(app, userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400336 } catch (NameNotFoundException e) {
337 result = -1;
338 }
339 return result;
340 }
341
342 public NetworkInfo getNetworkInfo() {
343 return mNetworkInfo;
344 }
345
Lorenzo Colitti60446162014-09-20 00:14:31 +0900346 private LinkProperties makeLinkProperties() {
347 boolean allowIPv4 = mConfig.allowIPv4;
348 boolean allowIPv6 = mConfig.allowIPv6;
349
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400350 LinkProperties lp = new LinkProperties();
Lorenzo Colitti60446162014-09-20 00:14:31 +0900351
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400352 lp.setInterfaceName(mInterface);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700353
Lorenzo Colitti60446162014-09-20 00:14:31 +0900354 if (mConfig.addresses != null) {
355 for (LinkAddress address : mConfig.addresses) {
356 lp.addLinkAddress(address);
357 allowIPv4 |= address.getAddress() instanceof Inet4Address;
358 allowIPv6 |= address.getAddress() instanceof Inet6Address;
359 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400360 }
Lorenzo Colitti60446162014-09-20 00:14:31 +0900361
362 if (mConfig.routes != null) {
363 for (RouteInfo route : mConfig.routes) {
364 lp.addRoute(route);
365 InetAddress address = route.getDestination().getAddress();
366 allowIPv4 |= address instanceof Inet4Address;
367 allowIPv6 |= address instanceof Inet6Address;
368 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400369 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700370
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400371 if (mConfig.dnsServers != null) {
372 for (String dnsServer : mConfig.dnsServers) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700373 InetAddress address = InetAddress.parseNumericAddress(dnsServer);
374 lp.addDnsServer(address);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900375 allowIPv4 |= address instanceof Inet4Address;
376 allowIPv6 |= address instanceof Inet6Address;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400377 }
378 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700379
Lorenzo Colitti60446162014-09-20 00:14:31 +0900380 if (!allowIPv4) {
381 lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
382 }
383 if (!allowIPv6) {
384 lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
385 }
386
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400387 // Concatenate search domains into a string.
388 StringBuilder buffer = new StringBuilder();
389 if (mConfig.searchDomains != null) {
390 for (String domain : mConfig.searchDomains) {
391 buffer.append(domain).append(' ');
392 }
393 }
394 lp.setDomains(buffer.toString().trim());
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700395
Lorenzo Colitti60446162014-09-20 00:14:31 +0900396 // TODO: Stop setting the MTU in jniCreate and set it here.
397
398 return lp;
399 }
400
401 private void agentConnect() {
402 LinkProperties lp = makeLinkProperties();
403
404 if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
405 mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
406 } else {
407 mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
408 }
409
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400410 mNetworkInfo.setIsAvailable(true);
411 mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700412
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700413 NetworkMisc networkMisc = new NetworkMisc();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700414 networkMisc.allowBypass = mConfig.allowBypass;
415
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400416 long token = Binder.clearCallingIdentity();
417 try {
418 mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700419 mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
Jeff Davidson05542602014-08-11 14:07:27 -0700420 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400421 public void unwanted() {
422 // We are user controlled, not driven by NetworkRequest.
Jeff Davidson05542602014-08-11 14:07:27 -0700423 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400424 };
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700425 } finally {
426 Binder.restoreCallingIdentity(token);
427 }
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700428
Paul Jensen0784eea2014-08-19 16:00:24 -0400429 addVpnUserLocked(mUserHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400430 // If we are owner assign all Restricted Users to this VPN
Paul Jensen0784eea2014-08-19 16:00:24 -0400431 if (mUserHandle == UserHandle.USER_OWNER) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400432 token = Binder.clearCallingIdentity();
433 List<UserInfo> users;
434 try {
435 users = UserManager.get(mContext).getUsers();
436 } finally {
437 Binder.restoreCallingIdentity(token);
438 }
439 for (UserInfo user : users) {
440 if (user.isRestricted()) {
441 addVpnUserLocked(user.id);
442 }
443 }
444 }
445 mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
446 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700447
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400448 private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
449 networkInfo.setIsAvailable(false);
450 networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
451 if (networkAgent != null) {
452 networkAgent.sendNetworkInfo(networkInfo);
453 }
454 }
455
456 private void agentDisconnect(NetworkAgent networkAgent) {
457 NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
458 agentDisconnect(networkInfo, networkAgent);
459 }
460
461 private void agentDisconnect() {
462 if (mNetworkInfo.isConnected()) {
463 agentDisconnect(mNetworkInfo, mNetworkAgent);
464 mNetworkAgent = null;
465 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700466 }
467
468 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700469 * Establish a VPN network and return the file descriptor of the VPN
470 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700471 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700472 *
473 * @param config The parameters to configure the network.
474 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700475 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700476 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700477 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700478 UserManager mgr = UserManager.get(mContext);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400479 if (Binder.getCallingUid() != mOwnerUID) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700480 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700481 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700482 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700483 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
484 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700485 long token = Binder.clearCallingIdentity();
486 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700487 // Restricted users are not allowed to create VPNs, they are tied to Owner
Paul Jensen0784eea2014-08-19 16:00:24 -0400488 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400489 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700490 throw new SecurityException("Restricted users cannot establish VPNs");
491 }
492
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700493 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
Paul Jensen0784eea2014-08-19 16:00:24 -0400494 null, 0, mUserHandle);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700495 if (info == null) {
496 throw new SecurityException("Cannot find " + config.user);
497 }
498 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
499 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
500 }
501 } catch (RemoteException e) {
502 throw new SecurityException("Cannot find " + config.user);
503 } finally {
504 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700505 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700506
Chad Brubaker850eb672014-03-21 21:02:47 +0000507 // Save the old config in case we need to go back.
508 VpnConfig oldConfig = mConfig;
509 String oldInterface = mInterface;
510 Connection oldConnection = mConnection;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400511 NetworkAgent oldNetworkAgent = mNetworkAgent;
512 mNetworkAgent = null;
513 List<UidRange> oldUsers = mVpnUsers;
Chad Brubaker850eb672014-03-21 21:02:47 +0000514
Chia-chi Yehe9107902011-07-02 01:48:50 -0700515 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700516 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700517 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700518 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700519 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700520
Chad Brubakerc2865192013-07-10 14:46:23 -0700521 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700522 StringBuilder builder = new StringBuilder();
523 for (LinkAddress address : config.addresses) {
524 builder.append(" " + address);
525 }
526 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700527 throw new IllegalArgumentException("At least one address must be specified");
528 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700529 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700530 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
Paul Jensen0784eea2014-08-19 16:00:24 -0400531 new UserHandle(mUserHandle))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700532 throw new IllegalStateException("Cannot bind " + config.user);
533 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000534
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700535 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700536 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700537
538 // Fill more values.
539 config.user = mPackage;
540 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700541 config.startTime = SystemClock.elapsedRealtime();
542 mConfig = config;
Chad Brubaker850eb672014-03-21 21:02:47 +0000543
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700544 // Set up forwarding and DNS rules.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400545 mVpnUsers = new ArrayList<UidRange>();
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700546
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400547 agentConnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000548
549 if (oldConnection != null) {
550 mContext.unbindService(oldConnection);
551 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400552 // Remove the old tun's user forwarding rules
553 // The new tun's user rules have already been added so they will take over
554 // as rules are deleted. This prevents data leakage as the rules are moved over.
555 agentDisconnect(oldNetworkAgent);
Chad Brubaker850eb672014-03-21 21:02:47 +0000556 if (oldInterface != null && !oldInterface.equals(interfaze)) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000557 jniReset(oldInterface);
558 }
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700559
560 try {
561 IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
562 } catch (IOException e) {
563 throw new IllegalStateException(
564 "Cannot set tunnel's fd as blocking=" + config.blocking, e);
565 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000566 } catch (RuntimeException e) {
Chad Brubaker850eb672014-03-21 21:02:47 +0000567 IoUtils.closeQuietly(tun);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400568 agentDisconnect();
Chad Brubaker850eb672014-03-21 21:02:47 +0000569 // restore old state
570 mConfig = oldConfig;
571 mConnection = oldConnection;
572 mVpnUsers = oldUsers;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400573 mNetworkAgent = oldNetworkAgent;
Chad Brubaker850eb672014-03-21 21:02:47 +0000574 mInterface = oldInterface;
575 throw e;
Chad Brubakerc2865192013-07-10 14:46:23 -0700576 }
Chad Brubaker850eb672014-03-21 21:02:47 +0000577 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700578 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700579 }
580
Chad Brubakerc2865192013-07-10 14:46:23 -0700581 private boolean isRunningLocked() {
582 return mVpnUsers != null;
583 }
584
Paul Jensen0784eea2014-08-19 16:00:24 -0400585 // Note: Return type guarantees results are deduped and sorted, which callers require.
586 private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
587 SortedSet<Integer> uids = new TreeSet<Integer>();
588 for (String app : packageNames) {
589 int uid = getAppUid(app, userHandle);
590 if (uid != -1) uids.add(uid);
591 }
592 return uids;
593 }
594
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400595 // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
Paul Jensen0784eea2014-08-19 16:00:24 -0400596 private void addVpnUserLocked(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700597 if (!isRunningLocked()) {
598 throw new IllegalStateException("VPN is not active");
599 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700600
Paul Jensen0784eea2014-08-19 16:00:24 -0400601 if (mConfig.allowedApplications != null) {
602 // Add ranges covering all UIDs for allowedApplications.
603 int start = -1, stop = -1;
604 for (int uid : getAppsUids(mConfig.allowedApplications, userHandle)) {
605 if (start == -1) {
606 start = uid;
607 } else if (uid != stop + 1) {
608 mVpnUsers.add(new UidRange(start, stop));
609 start = uid;
610 }
611 stop = uid;
612 }
613 if (start != -1) mVpnUsers.add(new UidRange(start, stop));
614 } else if (mConfig.disallowedApplications != null) {
615 // Add all ranges for user skipping UIDs for disallowedApplications.
616 final UidRange userRange = UidRange.createForUser(userHandle);
617 int start = userRange.start;
618 for (int uid : getAppsUids(mConfig.disallowedApplications, userHandle)) {
619 if (uid == start) {
620 start++;
621 } else {
622 mVpnUsers.add(new UidRange(start, uid - 1));
623 start = uid + 1;
624 }
625 }
626 if (start <= userRange.stop) mVpnUsers.add(new UidRange(start, userRange.stop));
627 } else {
628 // Add all UIDs for the user.
629 mVpnUsers.add(UidRange.createForUser(userHandle));
630 }
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700631
632 prepareStatusIntent();
Chad Brubakerc2865192013-07-10 14:46:23 -0700633 }
634
Paul Jensen0784eea2014-08-19 16:00:24 -0400635 // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
636 // apply to userHandle.
637 private List<UidRange> uidRangesForUser(int userHandle) {
638 final UidRange userRange = UidRange.createForUser(userHandle);
639 final List<UidRange> ranges = new ArrayList<UidRange>();
640 for (UidRange range : mVpnUsers) {
641 if (range.start >= userRange.start && range.stop <= userRange.stop) {
642 ranges.add(range);
643 }
644 }
645 return ranges;
646 }
647
648 private void removeVpnUserLocked(int userHandle) {
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700649 if (!isRunningLocked()) {
650 throw new IllegalStateException("VPN is not active");
651 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400652 final List<UidRange> ranges = uidRangesForUser(userHandle);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700653 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400654 mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700655 }
Paul Jensen0784eea2014-08-19 16:00:24 -0400656 mVpnUsers.removeAll(ranges);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700657 mStatusIntent = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700658 }
659
Paul Jensen0784eea2014-08-19 16:00:24 -0400660 private void onUserAdded(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700661 // If the user is restricted tie them to the owner's VPN
662 synchronized(Vpn.this) {
663 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400664 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700665 if (user.isRestricted()) {
666 try {
Paul Jensen0784eea2014-08-19 16:00:24 -0400667 addVpnUserLocked(userHandle);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400668 if (mNetworkAgent != null) {
Paul Jensen0784eea2014-08-19 16:00:24 -0400669 final List<UidRange> ranges = uidRangesForUser(userHandle);
670 mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400671 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700672 } catch (Exception e) {
673 Log.wtf(TAG, "Failed to add restricted user to owner", e);
674 }
675 }
676 }
677 }
678
Paul Jensen0784eea2014-08-19 16:00:24 -0400679 private void onUserRemoved(int userHandle) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700680 // clean up if restricted
681 synchronized(Vpn.this) {
682 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400683 UserInfo user = mgr.getUserInfo(userHandle);
Chad Brubakerc2865192013-07-10 14:46:23 -0700684 if (user.isRestricted()) {
685 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;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700727 mInterface = null;
728 if (mConnection != null) {
729 mContext.unbindService(mConnection);
730 mConnection = null;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400731 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700732 } else if (mLegacyVpnRunner != null) {
733 mLegacyVpnRunner.exit();
734 mLegacyVpnRunner = null;
735 }
736 }
737 }
738 }
739 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700740
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700741 private void enforceControlPermission() {
742 // System user is allowed to control VPN.
743 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
744 return;
745 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700746 int appId = UserHandle.getAppId(Binder.getCallingUid());
747 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700748 try {
Nick Kralevich212a1952013-10-18 17:48:39 -0700749 // System VPN dialogs are also allowed to control VPN.
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700750 PackageManager pm = mContext.getPackageManager();
751 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Nick Kralevich212a1952013-10-18 17:48:39 -0700752 if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700753 return;
754 }
Jason Monke47df842014-07-30 16:41:52 -0400755 // SystemUI dialogs are also allowed to control VPN.
756 ApplicationInfo sysUiApp = pm.getApplicationInfo("com.android.systemui", 0);
757 if (((sysUiApp.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == sysUiApp.uid)) {
758 return;
759 }
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700760 } catch (Exception e) {
761 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700762 } finally {
763 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700764 }
765
766 throw new SecurityException("Unauthorized Caller");
767 }
768
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700769 private class Connection implements ServiceConnection {
770 private IBinder mService;
771
772 @Override
773 public void onServiceConnected(ComponentName name, IBinder service) {
774 mService = service;
775 }
776
777 @Override
778 public void onServiceDisconnected(ComponentName name) {
779 mService = null;
780 }
781 }
782
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700783 private void prepareStatusIntent() {
784 final long token = Binder.clearCallingIdentity();
785 try {
786 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
787 } finally {
788 Binder.restoreCallingIdentity(token);
789 }
790 }
791
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700792 public synchronized boolean addAddress(String address, int prefixLength) {
793 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
794 return false;
795 }
796 boolean success = jniAddAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900797 if (mNetworkAgent != null) {
798 mNetworkAgent.sendLinkProperties(makeLinkProperties());
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700799 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700800 return success;
801 }
802
803 public synchronized boolean removeAddress(String address, int prefixLength) {
804 if (Binder.getCallingUid() != mOwnerUID || mInterface == null || mNetworkAgent == null) {
805 return false;
806 }
807 boolean success = jniDelAddress(mInterface, address, prefixLength);
Lorenzo Colitti60446162014-09-20 00:14:31 +0900808 if (mNetworkAgent != null) {
809 mNetworkAgent.sendLinkProperties(makeLinkProperties());
810 }
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700811 return success;
812 }
813
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700814 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700815 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700816 private native int jniSetAddresses(String interfaze, String addresses);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700817 private native void jniReset(String interfaze);
818 private native int jniCheck(String interfaze);
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700819 private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
820 private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700821
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900822 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
823 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700824 // Currently legacy VPN only works on IPv4.
825 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900826 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700827 }
828 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700829
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900830 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700831 }
832
833 /**
834 * Start legacy VPN, controlling native daemons as needed. Creates a
835 * secondary thread to perform connection work, returning quickly.
836 */
837 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800838 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800839 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700840 throw new IllegalStateException("KeyStore isn't unlocked");
841 }
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400842 UserManager mgr = UserManager.get(mContext);
Paul Jensen0784eea2014-08-19 16:00:24 -0400843 UserInfo user = mgr.getUserInfo(mUserHandle);
Julia Reynoldsf5116d02014-07-01 11:10:41 -0400844 if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
845 throw new SecurityException("Restricted users cannot establish VPNs");
846 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700847
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900848 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
849 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
850 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700851
852 // Load certificates.
853 String privateKey = "";
854 String userCert = "";
855 String caCert = "";
856 String serverCert = "";
857 if (!profile.ipsecUserCert.isEmpty()) {
858 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
859 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700860 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700861 }
862 if (!profile.ipsecCaCert.isEmpty()) {
863 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700864 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700865 }
866 if (!profile.ipsecServerCert.isEmpty()) {
867 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700868 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700869 }
870 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
871 throw new IllegalStateException("Cannot load credentials");
872 }
873
874 // Prepare arguments for racoon.
875 String[] racoon = null;
876 switch (profile.type) {
877 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
878 racoon = new String[] {
879 iface, profile.server, "udppsk", profile.ipsecIdentifier,
880 profile.ipsecSecret, "1701",
881 };
882 break;
883 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
884 racoon = new String[] {
885 iface, profile.server, "udprsa", privateKey, userCert,
886 caCert, serverCert, "1701",
887 };
888 break;
889 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
890 racoon = new String[] {
891 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
892 profile.ipsecSecret, profile.username, profile.password, "", gateway,
893 };
894 break;
895 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
896 racoon = new String[] {
897 iface, profile.server, "xauthrsa", privateKey, userCert,
898 caCert, serverCert, profile.username, profile.password, "", gateway,
899 };
900 break;
901 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
902 racoon = new String[] {
903 iface, profile.server, "hybridrsa",
904 caCert, serverCert, profile.username, profile.password, "", gateway,
905 };
906 break;
907 }
908
909 // Prepare arguments for mtpd.
910 String[] mtpd = null;
911 switch (profile.type) {
912 case VpnProfile.TYPE_PPTP:
913 mtpd = new String[] {
914 iface, "pptp", profile.server, "1723",
915 "name", profile.username, "password", profile.password,
916 "linkname", "vpn", "refuse-eap", "nodefaultroute",
917 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
918 (profile.mppe ? "+mppe" : "nomppe"),
919 };
920 break;
921 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
922 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
923 mtpd = new String[] {
924 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
925 "name", profile.username, "password", profile.password,
926 "linkname", "vpn", "refuse-eap", "nodefaultroute",
927 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
928 };
929 break;
930 }
931
932 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700933 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700934 config.user = profile.key;
935 config.interfaze = iface;
936 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700937
938 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700939 if (!profile.dnsServers.isEmpty()) {
940 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
941 }
942 if (!profile.searchDomains.isEmpty()) {
943 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
944 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700945 startLegacyVpn(config, racoon, mtpd);
946 }
947
948 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
949 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700950
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700951 // Prepare for the new request. This also checks the caller.
952 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700953 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700954
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700955 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700956 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
957 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700958 }
959
Jeff Sharkey899223b2012-08-04 15:24:58 -0700960 public synchronized void stopLegacyVpn() {
961 if (mLegacyVpnRunner != null) {
962 mLegacyVpnRunner.exit();
963 mLegacyVpnRunner = null;
964
965 synchronized (LegacyVpnRunner.TAG) {
966 // wait for old thread to completely finish before spinning up
967 // new instance, otherwise state updates can be out of order.
968 }
969 }
970 }
971
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700972 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700973 * Return the information of the current ongoing legacy VPN.
974 */
975 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700976 // Check if the caller is authorized.
977 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700978 if (mLegacyVpnRunner == null) return null;
979
980 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700981 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700982 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
Jeff Davidson90b1b9f2014-08-22 13:05:43 -0700983 if (mNetworkInfo.isConnected()) {
984 info.intent = mStatusIntent;
985 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700986 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700987 }
988
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700989 public VpnConfig getLegacyVpnConfig() {
990 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700991 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700992 } else {
993 return null;
994 }
995 }
996
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700997 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700998 * Bringing up a VPN connection takes time, and that is all this thread
999 * does. Here we have plenty of time. The only thing we need to take
1000 * care of is responding to interruptions as soon as possible. Otherwise
1001 * requests will be piled up. This can be done in a Handler as a state
1002 * machine, but it is much easier to read in the current form.
1003 */
1004 private class LegacyVpnRunner extends Thread {
1005 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001006
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001007 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001008 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001009 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001010 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001011 private final AtomicInteger mOuterConnection =
1012 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001013
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001014 private long mTimer = -1;
1015
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001016 /**
1017 * Watch for the outer connection (passing in the constructor) going away.
1018 */
1019 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1020 @Override
1021 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -07001022 if (!mEnableTeardown) return;
1023
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001024 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1025 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1026 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1027 NetworkInfo info = (NetworkInfo)intent.getExtra(
1028 ConnectivityManager.EXTRA_NETWORK_INFO);
1029 if (info != null && !info.isConnectedOrConnecting()) {
1030 try {
1031 mObserver.interfaceStatusChanged(mOuterInterface, false);
1032 } catch (RemoteException e) {}
1033 }
1034 }
1035 }
1036 }
1037 };
1038
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001039 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001040 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001041 mConfig = config;
1042 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -07001043 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001044 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001045 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001046
1047 // This is the interface which VPN is running on,
1048 // mConfig.interfaze will change to point to OUR
1049 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001050 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001051 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001052 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001053 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001054
1055 try {
1056 mOuterConnection.set(
1057 mConnService.findConnectionTypeForIface(mOuterInterface));
1058 } catch (Exception e) {
1059 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
1060 }
1061
1062 IntentFilter filter = new IntentFilter();
1063 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1064 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001065 }
1066
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001067 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -07001068 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -07001069 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1070 exit();
1071 }
1072 }
1073
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001074 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001075 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001076 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001077 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -07001078 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001079 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001080 agentDisconnect();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07001081 try {
1082 mContext.unregisterReceiver(mBroadcastReceiver);
1083 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001084 }
1085
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001086 @Override
1087 public void run() {
1088 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001089 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001090 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001091 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001092 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001093 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001094 }
1095 }
1096
1097 private void checkpoint(boolean yield) throws InterruptedException {
1098 long now = SystemClock.elapsedRealtime();
1099 if (mTimer == -1) {
1100 mTimer = now;
1101 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -07001102 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001103 Thread.sleep(yield ? 200 : 1);
1104 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -07001105 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001106 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001107 }
1108 }
1109
1110 private void execute() {
1111 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001112 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001113 try {
1114 // Initialize the timer.
1115 checkpoint(false);
1116
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001117 // Wait for the daemons to stop.
1118 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001119 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001120 checkpoint(true);
1121 }
1122 }
1123
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001124 // Clear the previous state.
1125 File state = new File("/data/misc/vpn/state");
1126 state.delete();
1127 if (state.exists()) {
1128 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001129 }
Chia-chi Yehc1872732011-12-08 16:51:41 -08001130 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001131 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001132
Chia-chi Yehe9107902011-07-02 01:48:50 -07001133 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001134 boolean restart = false;
1135 for (String[] arguments : mArguments) {
1136 restart = restart || (arguments != null);
1137 }
1138 if (!restart) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001139 agentDisconnect();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001140 return;
1141 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001142 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001143
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001144 // Start the daemon with arguments.
1145 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001146 String[] arguments = mArguments[i];
1147 if (arguments == null) {
1148 continue;
1149 }
1150
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001151 // Start the daemon.
1152 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001153 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001154
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001155 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001156 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001157 checkpoint(true);
1158 }
1159
1160 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001161 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001162 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001163 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001164
1165 // Wait for the socket to connect.
1166 while (true) {
1167 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001168 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001169 break;
1170 } catch (Exception e) {
1171 // ignore
1172 }
1173 checkpoint(true);
1174 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001175 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001176
1177 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001178 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001179 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001180 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001181 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001182 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001183 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001184 out.write(bytes.length >> 8);
1185 out.write(bytes.length);
1186 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001187 checkpoint(false);
1188 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001189 out.write(0xFF);
1190 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001191 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001192
1193 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001194 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001195 while (true) {
1196 try {
1197 if (in.read() == -1) {
1198 break;
1199 }
1200 } catch (Exception e) {
1201 // ignore
1202 }
1203 checkpoint(true);
1204 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001205 }
1206
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001207 // Wait for the daemons to create the new state.
1208 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001209 // Check if a running daemon is dead.
1210 for (int i = 0; i < mDaemons.length; ++i) {
1211 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001212 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001213 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001214 }
1215 }
1216 checkpoint(true);
1217 }
1218
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001219 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001220 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Lorenzo Colitti50262792014-09-19 01:53:35 +09001221 if (parameters.length != 7) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001222 throw new IllegalStateException("Cannot parse the state");
1223 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001224
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001225 // Set the interface and the addresses in the config.
1226 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001227
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001228 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001229 // Set the routes if they are not set in the config.
1230 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001231 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001232 }
1233
1234 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001235 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001236 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001237 if (!dnsServers.isEmpty()) {
1238 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1239 }
1240 }
1241
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001242 // Set the search domains if they are not set in the config.
1243 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1244 String searchDomains = parameters[4].trim();
1245 if (!searchDomains.isEmpty()) {
1246 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1247 }
1248 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001249
Lorenzo Colitti50262792014-09-19 01:53:35 +09001250 // Add a throw route for the VPN server endpoint, if one was specified.
1251 String endpoint = parameters[5];
1252 if (!endpoint.isEmpty()) {
1253 try {
1254 InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1255 if (addr instanceof Inet4Address) {
1256 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1257 } else if (addr instanceof Inet6Address) {
1258 mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1259 } else {
1260 Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1261 }
1262 } catch (IllegalArgumentException e) {
1263 Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1264 }
1265 }
1266
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001267 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001268 synchronized (Vpn.this) {
Vinit Deshapnde2b862e52013-10-02 11:50:39 -07001269 // Set the start time
1270 mConfig.startTime = SystemClock.elapsedRealtime();
1271
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001272 // Check if the thread is interrupted while we are waiting.
1273 checkpoint(false);
1274
Chia-chi Yehe9107902011-07-02 01:48:50 -07001275 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001276 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001277 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001278 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001279
1280 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001281 mInterface = mConfig.interfaze;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001282 mVpnUsers = new ArrayList<UidRange>();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001283
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001284 agentConnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001285
1286 Log.i(TAG, "Connected!");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001287 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001288 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001289 Log.i(TAG, "Aborting", e);
Lorenzo Colitti43840602014-08-20 16:01:44 -07001290 updateState(DetailedState.FAILED, e.getMessage());
Chia-chi Yehe9107902011-07-02 01:48:50 -07001291 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001292 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001293 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001294 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001295 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001296 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001297 }
1298 }
1299
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001300 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001301 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001302 agentDisconnect();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001303 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001304 }
1305 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001306
1307 /**
1308 * Monitor the daemons we started, moving to disconnected state if the
1309 * underlying services fail.
1310 */
1311 private void monitorDaemons() {
1312 if (!mNetworkInfo.isConnected()) {
1313 return;
1314 }
1315
1316 try {
1317 while (true) {
1318 Thread.sleep(2000);
1319 for (int i = 0; i < mDaemons.length; i++) {
1320 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1321 return;
1322 }
1323 }
1324 }
1325 } catch (InterruptedException e) {
1326 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1327 } finally {
1328 for (String daemon : mDaemons) {
1329 SystemService.stop(daemon);
1330 }
1331
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001332 agentDisconnect();
Jeff Sharkey899223b2012-08-04 15:24:58 -07001333 }
1334 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001335 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001336}