blob: 8cc5b4f69cd98757c211d04e42aefc3738c88681 [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;
20
Chad Brubaker4ca19e82013-06-14 11:16:51 -070021import android.app.AppGlobals;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070022import android.app.Notification;
23import android.app.NotificationManager;
Jeff Sharkey899223b2012-08-04 15:24:58 -070024import android.app.PendingIntent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070025import android.content.BroadcastReceiver;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070026import android.content.ComponentName;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070027import android.content.Context;
28import android.content.Intent;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070029import android.content.IntentFilter;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.content.ServiceConnection;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070031import android.content.pm.ApplicationInfo;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070032import android.content.pm.IPackageManager;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070033import android.content.pm.PackageManager;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.content.pm.ResolveInfo;
Chad Brubakerc2865192013-07-10 14:46:23 -070035import android.content.pm.UserInfo;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070036import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.drawable.Drawable;
Jeff Sharkey899223b2012-08-04 15:24:58 -070039import android.net.BaseNetworkStateTracker;
40import 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;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070043import android.net.LinkAddress;
Jeff Sharkey82f85212012-08-24 11:17:25 -070044import android.net.LinkProperties;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070045import android.net.LocalSocket;
46import android.net.LocalSocketAddress;
Jeff Sharkey899223b2012-08-04 15:24:58 -070047import android.net.NetworkInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -070048import android.net.RouteInfo;
Jeff Sharkey899223b2012-08-04 15:24:58 -070049import android.net.NetworkInfo.DetailedState;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070050import android.os.Binder;
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -080051import android.os.FileUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070052import android.os.IBinder;
Jeff Sharkey899223b2012-08-04 15:24:58 -070053import android.os.INetworkManagementService;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070054import android.os.Parcel;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070055import android.os.ParcelFileDescriptor;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070056import android.os.Process;
Jeff Sharkey899223b2012-08-04 15:24:58 -070057import android.os.RemoteException;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070058import android.os.SystemClock;
Jeff Sharkey088f29f2012-08-05 14:55:04 -070059import android.os.SystemService;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070060import android.os.UserHandle;
Chad Brubakerc2865192013-07-10 14:46:23 -070061import android.os.UserManager;
Jeff Sharkey82f85212012-08-24 11:17:25 -070062import android.security.Credentials;
63import android.security.KeyStore;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070064import android.util.Log;
Chad Brubakerc2865192013-07-10 14:46:23 -070065import android.util.SparseBooleanArray;
Jeff Sharkey82f85212012-08-24 11:17:25 -070066import android.widget.Toast;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070067
Chad Brubakerc2865192013-07-10 14:46:23 -070068import com.android.internal.annotations.GuardedBy;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070069import com.android.internal.R;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070070import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070071import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070072import com.android.internal.net.VpnProfile;
Jeff Sharkey899223b2012-08-04 15:24:58 -070073import com.android.internal.util.Preconditions;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070074import com.android.server.ConnectivityService.VpnCallback;
Jeff Sharkey899223b2012-08-04 15:24:58 -070075import com.android.server.net.BaseNetworkObserver;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076
Chia-chi Yeh97a61562011-07-14 15:05:05 -070077import java.io.File;
Chia-chi Yeh97a61562011-07-14 15:05:05 -070078import java.io.InputStream;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070079import java.io.OutputStream;
Jeff Sharkey82f85212012-08-24 11:17:25 -070080import java.net.Inet4Address;
81import java.net.InetAddress;
Elliott Hughesd396a442013-06-28 16:24:48 -070082import java.nio.charset.StandardCharsets;
Chia-chi Yeh41d16852011-07-01 02:12:06 -070083import java.util.Arrays;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070084import java.util.List;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -070085import java.util.concurrent.atomic.AtomicInteger;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -070086
Jeff Sharkey065b2992012-08-05 14:16:48 -070087import libcore.io.IoUtils;
88
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070089/**
90 * @hide
91 */
Jeff Sharkey899223b2012-08-04 15:24:58 -070092public class Vpn extends BaseNetworkStateTracker {
93 private static final String TAG = "Vpn";
94 private static final boolean LOGD = true;
95
96 // TODO: create separate trackers for each unique VPN to support
97 // automated reconnection
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070099 private final VpnCallback mCallback;
100
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700101 private String mPackage = VpnConfig.LEGACY_VPN;
102 private String mInterface;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700103 private Connection mConnection;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700104 private LegacyVpnRunner mLegacyVpnRunner;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700105 private PendingIntent mStatusIntent;
Jeff Sharkey57666932013-04-30 17:01:57 -0700106 private volatile boolean mEnableNotif = true;
107 private volatile boolean mEnableTeardown = true;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700108 private final IConnectivityManager mConnService;
Chad Brubakerc2865192013-07-10 14:46:23 -0700109 private VpnConfig mConfig;
110
111 /* list of users using this VPN. */
112 @GuardedBy("this")
113 private SparseBooleanArray mVpnUsers = null;
114 private BroadcastReceiver mUserIntentReceiver = null;
115
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700116 private final int mUserId;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700118 public Vpn(Context context, VpnCallback callback, INetworkManagementService netService,
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700119 IConnectivityManager connService, int userId) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700120 // TODO: create dedicated TYPE_VPN network type
121 super(ConnectivityManager.TYPE_DUMMY);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700122 mContext = context;
123 mCallback = callback;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700124 mConnService = connService;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700125 mUserId = userId;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700126
127 try {
128 netService.registerObserver(mObserver);
129 } catch (RemoteException e) {
130 Log.wtf(TAG, "Problem registering observer", e);
131 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700132 if (userId == UserHandle.USER_OWNER) {
133 // Owner's VPN also needs to handle restricted users
134 mUserIntentReceiver = new BroadcastReceiver() {
135 @Override
136 public void onReceive(Context context, Intent intent) {
137 final String action = intent.getAction();
138 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
139 UserHandle.USER_NULL);
140 if (userId == UserHandle.USER_NULL) return;
141
142 if (Intent.ACTION_USER_ADDED.equals(action)) {
143 onUserAdded(userId);
144 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
145 onUserRemoved(userId);
146 }
147 }
148 };
149
150 IntentFilter intentFilter = new IntentFilter();
151 intentFilter.addAction(Intent.ACTION_USER_ADDED);
152 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
153 mContext.registerReceiverAsUser(
154 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
155 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700156 }
157
Jeff Sharkey57666932013-04-30 17:01:57 -0700158 /**
159 * Set if this object is responsible for showing its own notifications. When
160 * {@code false}, notifications are handled externally by someone else.
161 */
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700162 public void setEnableNotifications(boolean enableNotif) {
163 mEnableNotif = enableNotif;
164 }
165
Jeff Sharkey57666932013-04-30 17:01:57 -0700166 /**
167 * Set if this object is responsible for watching for {@link NetworkInfo}
168 * teardown. When {@code false}, teardown is handled externally by someone
169 * else.
170 */
171 public void setEnableTeardown(boolean enableTeardown) {
172 mEnableTeardown = enableTeardown;
173 }
174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 @Override
176 protected void startMonitoringInternal() {
177 // Ignored; events are sent through callbacks for now
178 }
179
180 @Override
181 public boolean teardown() {
182 // TODO: finish migration to unique tracker for each VPN
183 throw new UnsupportedOperationException();
184 }
185
186 @Override
187 public boolean reconnect() {
188 // TODO: finish migration to unique tracker for each VPN
189 throw new UnsupportedOperationException();
190 }
191
192 @Override
193 public String getTcpBufferSizesPropName() {
194 return PROP_TCP_BUFFER_UNKNOWN;
195 }
196
197 /**
198 * Update current state, dispaching event to listeners.
199 */
200 private void updateState(DetailedState detailedState, String reason) {
201 if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
202 mNetworkInfo.setDetailedState(detailedState, reason, null);
203 mCallback.onStateChanged(new NetworkInfo(mNetworkInfo));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700204 }
205
206 /**
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700207 * Prepare for a VPN application. This method is designed to solve
208 * race conditions. It first compares the current prepared package
209 * with {@code oldPackage}. If they are the same, the prepared
210 * package is revoked and replaced with {@code newPackage}. If
211 * {@code oldPackage} is {@code null}, the comparison is omitted.
212 * If {@code newPackage} is the same package or {@code null}, the
213 * revocation is omitted. This method returns {@code true} if the
214 * operation is succeeded.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700215 *
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700216 * Legacy VPN is handled specially since it is not a real package.
217 * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
218 * it can be revoked by itself.
219 *
220 * @param oldPackage The package name of the old VPN application.
221 * @param newPackage The package name of the new VPN application.
222 * @return true if the operation is succeeded.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700223 */
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700224 public synchronized boolean prepare(String oldPackage, String newPackage) {
225 // Return false if the package does not match.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700226 if (oldPackage != null && !oldPackage.equals(mPackage)) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700227 return false;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700228 }
229
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700230 // Return true if we do not need to revoke.
231 if (newPackage == null ||
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700232 (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700233 return true;
234 }
235
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700236 // Check if the caller is authorized.
237 enforceControlPermission();
Chia-chi Yehe9107902011-07-02 01:48:50 -0700238
Chia-chi Yehe9107902011-07-02 01:48:50 -0700239 // Reset the interface and hide the notification.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700240 if (mInterface != null) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700241 final long token = Binder.clearCallingIdentity();
242 try {
243 mCallback.restore();
Chad Brubakerc2865192013-07-10 14:46:23 -0700244 final int size = mVpnUsers.size();
245 for (int i = 0; i < size; i++) {
246 int user = mVpnUsers.keyAt(i);
247 mCallback.clearUserForwarding(mInterface, user);
248 hideNotification(user);
249 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700250
251 mCallback.clearMarkedForwarding(mInterface);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700252 } finally {
253 Binder.restoreCallingIdentity(token);
254 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700255 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700256 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700257 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700258 }
259
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700260 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700261 if (mConnection != null) {
262 try {
263 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
264 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
265 } catch (Exception e) {
266 // ignore
267 }
268 mContext.unbindService(mConnection);
269 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700270 } else if (mLegacyVpnRunner != null) {
271 mLegacyVpnRunner.exit();
272 mLegacyVpnRunner = null;
273 }
274
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700275 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
276 mPackage = newPackage;
Chad Brubakerc2865192013-07-10 14:46:23 -0700277 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700278 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700279 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700280 }
281
282 /**
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700283 * Protect a socket from routing changes by binding it to the given
284 * interface. The socket is NOT closed by this method.
285 *
286 * @param socket The socket to be bound.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700287 * @param interfaze The name of the interface.
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700288 */
289 public void protect(ParcelFileDescriptor socket, String interfaze) throws Exception {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700290
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700291 PackageManager pm = mContext.getPackageManager();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700292 int appUid = pm.getPackageUid(mPackage, mUserId);
293 if (Binder.getCallingUid() != appUid) {
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700294 throw new SecurityException("Unauthorized Caller");
295 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700296 // protect the socket from routing rules
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700297 final long token = Binder.clearCallingIdentity();
298 try {
299 mCallback.protect(socket);
300 } finally {
301 Binder.restoreCallingIdentity(token);
302 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700303 // bind the socket to the interface
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700304 jniProtect(socket.getFd(), interfaze);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700305
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700306 }
307
308 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700309 * Establish a VPN network and return the file descriptor of the VPN
310 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700311 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700312 *
313 * @param config The parameters to configure the network.
314 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700315 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700316 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700317 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700318 UserManager mgr = UserManager.get(mContext);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700319 PackageManager pm = mContext.getPackageManager();
320 ApplicationInfo app = null;
321 try {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700322 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
323 if (Binder.getCallingUid() != app.uid) {
324 return null;
325 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700326 } catch (Exception e) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700327 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700328 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700329 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700330 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
331 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700332 long token = Binder.clearCallingIdentity();
333 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700334 // Restricted users are not allowed to create VPNs, they are tied to Owner
335 UserInfo user = mgr.getUserInfo(mUserId);
336 if (user.isRestricted()) {
337 throw new SecurityException("Restricted users cannot establish VPNs");
338 }
339
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700340 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
341 null, 0, mUserId);
342 if (info == null) {
343 throw new SecurityException("Cannot find " + config.user);
344 }
345 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
346 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
347 }
348 } catch (RemoteException e) {
349 throw new SecurityException("Cannot find " + config.user);
350 } finally {
351 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700352 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700353
Chia-chi Yehe9107902011-07-02 01:48:50 -0700354 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700355 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700356 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700357 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700358 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700359
Chad Brubakerc2865192013-07-10 14:46:23 -0700360 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700361 StringBuilder builder = new StringBuilder();
362 for (LinkAddress address : config.addresses) {
363 builder.append(" " + address);
364 }
365 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700366 throw new IllegalArgumentException("At least one address must be specified");
367 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700368 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700369 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
370 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700371 throw new IllegalStateException("Cannot bind " + config.user);
372 }
373 if (mConnection != null) {
374 mContext.unbindService(mConnection);
375 }
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700376 if (mInterface != null && !mInterface.equals(interfaze)) {
377 jniReset(mInterface);
Chia-chi Yehf4e3bf82011-06-30 12:33:17 -0700378 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700379 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700380 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700381
382 // Fill more values.
383 config.user = mPackage;
384 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700385 config.startTime = SystemClock.elapsedRealtime();
386 mConfig = config;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700387 // Set up forwarding and DNS rules.
Chad Brubakerc2865192013-07-10 14:46:23 -0700388 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700389 token = Binder.clearCallingIdentity();
390 try {
391 mCallback.setMarkedForwarding(mInterface);
392 mCallback.setRoutes(interfaze, config.routes);
393 mCallback.override(mInterface, config.dnsServers, config.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -0700394 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700395
396 } finally {
397 Binder.restoreCallingIdentity(token);
398 }
399
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700400 } catch (RuntimeException e) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700401 updateState(DetailedState.FAILED, "establish");
Jeff Sharkey065b2992012-08-05 14:16:48 -0700402 IoUtils.closeQuietly(tun);
Chad Brubakerc2865192013-07-10 14:46:23 -0700403 // make sure marked forwarding is cleared if it was set
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700404 try {
405 mCallback.clearMarkedForwarding(mInterface);
406 } catch (Exception ingored) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700407 // ignored
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700408 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700409 throw e;
410 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700411 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700412
Chia-chi Yeh8909b102011-07-01 01:09:42 -0700413
Chad Brubakerc2865192013-07-10 14:46:23 -0700414 // If we are owner assign all Restricted Users to this VPN
415 if (mUserId == UserHandle.USER_OWNER) {
416 token = Binder.clearCallingIdentity();
417 try {
418 for (UserInfo user : mgr.getUsers()) {
419 if (user.isRestricted()) {
420 try {
421 addVpnUserLocked(user.id);
422 } catch (Exception e) {
423 Log.wtf(TAG, "Failed to add user " + user.id + " to owner's VPN");
424 }
425 }
426 }
427 } finally {
428 Binder.restoreCallingIdentity(token);
429 }
430 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700431 // TODO: ensure that contract class eventually marks as connected
432 updateState(DetailedState.AUTHENTICATING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700433 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700434 }
435
Chad Brubakerc2865192013-07-10 14:46:23 -0700436 private boolean isRunningLocked() {
437 return mVpnUsers != null;
438 }
439
440 private void addVpnUserLocked(int user) {
441 enforceControlPermission();
442
443 if (!isRunningLocked()) {
444 throw new IllegalStateException("VPN is not active");
445 }
446 // add the user
447 mCallback.addUserForwarding(mInterface, user);
448 mVpnUsers.put(user, true);
449
450 // show the notification
451 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
452 // Load everything for the user's notification
453 PackageManager pm = mContext.getPackageManager();
454 ApplicationInfo app = null;
455 try {
456 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
457 } catch (RemoteException e) {
458 throw new IllegalStateException("Invalid application");
459 }
460 String label = app.loadLabel(pm).toString();
461 // Load the icon and convert it into a bitmap.
462 Drawable icon = app.loadIcon(pm);
463 Bitmap bitmap = null;
464 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
465 int width = mContext.getResources().getDimensionPixelSize(
466 android.R.dimen.notification_large_icon_width);
467 int height = mContext.getResources().getDimensionPixelSize(
468 android.R.dimen.notification_large_icon_height);
469 icon.setBounds(0, 0, width, height);
470 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
471 Canvas c = new Canvas(bitmap);
472 icon.draw(c);
473 c.setBitmap(null);
474 }
475 showNotification(label, bitmap, user);
476 } else {
477 showNotification(null, null, user);
478 }
479 }
480
481 private void removeVpnUserLocked(int user) {
482 enforceControlPermission();
483
484 if (!isRunningLocked()) {
485 throw new IllegalStateException("VPN is not active");
486 }
487 mCallback.clearUserForwarding(mInterface, user);
488 mVpnUsers.delete(user);
489 hideNotification(user);
490 }
491
492 private void onUserAdded(int userId) {
493 // If the user is restricted tie them to the owner's VPN
494 synchronized(Vpn.this) {
495 UserManager mgr = UserManager.get(mContext);
496 UserInfo user = mgr.getUserInfo(userId);
497 if (user.isRestricted()) {
498 try {
499 addVpnUserLocked(userId);
500 } catch (Exception e) {
501 Log.wtf(TAG, "Failed to add restricted user to owner", e);
502 }
503 }
504 }
505 }
506
507 private void onUserRemoved(int userId) {
508 // clean up if restricted
509 synchronized(Vpn.this) {
510 UserManager mgr = UserManager.get(mContext);
511 UserInfo user = mgr.getUserInfo(userId);
512 if (user.isRestricted()) {
513 try {
514 removeVpnUserLocked(userId);
515 } catch (Exception e) {
516 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
517 }
518 }
519 }
520 }
521
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700522 /**
523 * Return the configuration of the currently running VPN.
524 */
525 public VpnConfig getVpnConfig() {
526 enforceControlPermission();
527 return mConfig;
528 }
529
Jeff Sharkey899223b2012-08-04 15:24:58 -0700530 @Deprecated
531 public synchronized void interfaceStatusChanged(String iface, boolean up) {
532 try {
533 mObserver.interfaceStatusChanged(iface, up);
534 } catch (RemoteException e) {
535 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700536 }
537 }
538
Jeff Sharkey899223b2012-08-04 15:24:58 -0700539 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
540 @Override
541 public void interfaceStatusChanged(String interfaze, boolean up) {
542 synchronized (Vpn.this) {
543 if (!up && mLegacyVpnRunner != null) {
544 mLegacyVpnRunner.check(interfaze);
545 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700546 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700547 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700548
Jeff Sharkey899223b2012-08-04 15:24:58 -0700549 @Override
550 public void interfaceRemoved(String interfaze) {
551 synchronized (Vpn.this) {
552 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
553 final long token = Binder.clearCallingIdentity();
554 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700555 final int size = mVpnUsers.size();
556 for (int i = 0; i < size; i++) {
557 int user = mVpnUsers.keyAt(i);
558 mCallback.clearUserForwarding(mInterface, user);
559 hideNotification(user);
560 }
561 mVpnUsers = null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700562 mCallback.clearMarkedForwarding(mInterface);
563
Jeff Sharkey899223b2012-08-04 15:24:58 -0700564 mCallback.restore();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700565 } finally {
566 Binder.restoreCallingIdentity(token);
567 }
568 mInterface = null;
569 if (mConnection != null) {
570 mContext.unbindService(mConnection);
571 mConnection = null;
572 updateState(DetailedState.DISCONNECTED, "interfaceRemoved");
573 } else if (mLegacyVpnRunner != null) {
574 mLegacyVpnRunner.exit();
575 mLegacyVpnRunner = null;
576 }
577 }
578 }
579 }
580 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700581
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700582 private void enforceControlPermission() {
583 // System user is allowed to control VPN.
584 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
585 return;
586 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700587 int appId = UserHandle.getAppId(Binder.getCallingUid());
588 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700589 try {
590 // System dialogs are also allowed to control VPN.
591 PackageManager pm = mContext.getPackageManager();
592 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700593 if (appId == app.uid) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700594 return;
595 }
596 } catch (Exception e) {
597 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700598 } finally {
599 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700600 }
601
602 throw new SecurityException("Unauthorized Caller");
603 }
604
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700605 private class Connection implements ServiceConnection {
606 private IBinder mService;
607
608 @Override
609 public void onServiceConnected(ComponentName name, IBinder service) {
610 mService = service;
611 }
612
613 @Override
614 public void onServiceDisconnected(ComponentName name) {
615 mService = null;
616 }
617 }
618
Chad Brubakerc2865192013-07-10 14:46:23 -0700619 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700620 if (!mEnableNotif) return;
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700621 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700622
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700623 NotificationManager nm = (NotificationManager)
624 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
625
626 if (nm != null) {
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700627 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
628 mContext.getString(R.string.vpn_title_long, label);
Chad Brubakerc2865192013-07-10 14:46:23 -0700629 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
630 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700631
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700632 Notification notification = new Notification.Builder(mContext)
633 .setSmallIcon(R.drawable.vpn_connected)
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700634 .setLargeIcon(icon)
635 .setContentTitle(title)
Chia-chi Yehf8905fd2011-06-14 16:35:02 -0700636 .setContentText(text)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700637 .setContentIntent(mStatusIntent)
Chia-chi Yeh50fe7092012-01-11 14:26:24 -0800638 .setDefaults(0)
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700639 .setOngoing(true)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700640 .build();
Chad Brubakerc2865192013-07-10 14:46:23 -0700641 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700642 }
643 }
644
Chad Brubakerc2865192013-07-10 14:46:23 -0700645 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700646 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700647 mStatusIntent = null;
648
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700649 NotificationManager nm = (NotificationManager)
650 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
651
652 if (nm != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700653 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700654 }
655 }
656
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700657 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700658 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700659 private native int jniSetAddresses(String interfaze, String addresses);
660 private native int jniSetRoutes(String interfaze, String routes);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700661 private native void jniReset(String interfaze);
662 private native int jniCheck(String interfaze);
663 private native void jniProtect(int socket, String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700664
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900665 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
666 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700667 // Currently legacy VPN only works on IPv4.
668 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900669 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700670 }
671 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700672
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900673 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700674 }
675
676 /**
677 * Start legacy VPN, controlling native daemons as needed. Creates a
678 * secondary thread to perform connection work, returning quickly.
679 */
680 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800681 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800682 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700683 throw new IllegalStateException("KeyStore isn't unlocked");
684 }
685
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900686 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
687 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
688 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700689
690 // Load certificates.
691 String privateKey = "";
692 String userCert = "";
693 String caCert = "";
694 String serverCert = "";
695 if (!profile.ipsecUserCert.isEmpty()) {
696 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
697 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700698 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700699 }
700 if (!profile.ipsecCaCert.isEmpty()) {
701 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700702 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700703 }
704 if (!profile.ipsecServerCert.isEmpty()) {
705 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700706 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700707 }
708 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
709 throw new IllegalStateException("Cannot load credentials");
710 }
711
712 // Prepare arguments for racoon.
713 String[] racoon = null;
714 switch (profile.type) {
715 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
716 racoon = new String[] {
717 iface, profile.server, "udppsk", profile.ipsecIdentifier,
718 profile.ipsecSecret, "1701",
719 };
720 break;
721 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
722 racoon = new String[] {
723 iface, profile.server, "udprsa", privateKey, userCert,
724 caCert, serverCert, "1701",
725 };
726 break;
727 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
728 racoon = new String[] {
729 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
730 profile.ipsecSecret, profile.username, profile.password, "", gateway,
731 };
732 break;
733 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
734 racoon = new String[] {
735 iface, profile.server, "xauthrsa", privateKey, userCert,
736 caCert, serverCert, profile.username, profile.password, "", gateway,
737 };
738 break;
739 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
740 racoon = new String[] {
741 iface, profile.server, "hybridrsa",
742 caCert, serverCert, profile.username, profile.password, "", gateway,
743 };
744 break;
745 }
746
747 // Prepare arguments for mtpd.
748 String[] mtpd = null;
749 switch (profile.type) {
750 case VpnProfile.TYPE_PPTP:
751 mtpd = new String[] {
752 iface, "pptp", profile.server, "1723",
753 "name", profile.username, "password", profile.password,
754 "linkname", "vpn", "refuse-eap", "nodefaultroute",
755 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
756 (profile.mppe ? "+mppe" : "nomppe"),
757 };
758 break;
759 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
760 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
761 mtpd = new String[] {
762 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
763 "name", profile.username, "password", profile.password,
764 "linkname", "vpn", "refuse-eap", "nodefaultroute",
765 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
766 };
767 break;
768 }
769
770 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700771 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700772 config.user = profile.key;
773 config.interfaze = iface;
774 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700775
776 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700777 if (!profile.dnsServers.isEmpty()) {
778 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
779 }
780 if (!profile.searchDomains.isEmpty()) {
781 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
782 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700783 startLegacyVpn(config, racoon, mtpd);
784 }
785
786 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
787 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700788
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700789 // Prepare for the new request. This also checks the caller.
790 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700791 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700792
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700793 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700794 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
795 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700796 }
797
Jeff Sharkey899223b2012-08-04 15:24:58 -0700798 public synchronized void stopLegacyVpn() {
799 if (mLegacyVpnRunner != null) {
800 mLegacyVpnRunner.exit();
801 mLegacyVpnRunner = null;
802
803 synchronized (LegacyVpnRunner.TAG) {
804 // wait for old thread to completely finish before spinning up
805 // new instance, otherwise state updates can be out of order.
806 }
807 }
808 }
809
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700810 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700811 * Return the information of the current ongoing legacy VPN.
812 */
813 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700814 // Check if the caller is authorized.
815 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700816 if (mLegacyVpnRunner == null) return null;
817
818 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700819 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700820 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
821 if (mNetworkInfo.isConnected()) {
822 info.intent = mStatusIntent;
823 }
824 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700825 }
826
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700827 public VpnConfig getLegacyVpnConfig() {
828 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700829 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700830 } else {
831 return null;
832 }
833 }
834
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700835 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700836 * Bringing up a VPN connection takes time, and that is all this thread
837 * does. Here we have plenty of time. The only thing we need to take
838 * care of is responding to interruptions as soon as possible. Otherwise
839 * requests will be piled up. This can be done in a Handler as a state
840 * machine, but it is much easier to read in the current form.
841 */
842 private class LegacyVpnRunner extends Thread {
843 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700844
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700845 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700846 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700847 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700848 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700849 private final AtomicInteger mOuterConnection =
850 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700851
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700852 private long mTimer = -1;
853
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700854 /**
855 * Watch for the outer connection (passing in the constructor) going away.
856 */
857 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
858 @Override
859 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700860 if (!mEnableTeardown) return;
861
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700862 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
863 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
864 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
865 NetworkInfo info = (NetworkInfo)intent.getExtra(
866 ConnectivityManager.EXTRA_NETWORK_INFO);
867 if (info != null && !info.isConnectedOrConnecting()) {
868 try {
869 mObserver.interfaceStatusChanged(mOuterInterface, false);
870 } catch (RemoteException e) {}
871 }
872 }
873 }
874 }
875 };
876
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700877 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700878 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700879 mConfig = config;
880 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700881 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700882 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700883 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700884
885 // This is the interface which VPN is running on,
886 // mConfig.interfaze will change to point to OUR
887 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700888 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700889 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700890 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700891 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700892
893 try {
894 mOuterConnection.set(
895 mConnService.findConnectionTypeForIface(mOuterInterface));
896 } catch (Exception e) {
897 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
898 }
899
900 IntentFilter filter = new IntentFilter();
901 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
902 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700903 }
904
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700905 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700906 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700907 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
908 exit();
909 }
910 }
911
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700912 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700913 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700914 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700915 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -0700916 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700917 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700918 updateState(DetailedState.DISCONNECTED, "exit");
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700919 try {
920 mContext.unregisterReceiver(mBroadcastReceiver);
921 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700922 }
923
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700924 @Override
925 public void run() {
926 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700927 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700928 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700929 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700930 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700931 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700932 }
933 }
934
935 private void checkpoint(boolean yield) throws InterruptedException {
936 long now = SystemClock.elapsedRealtime();
937 if (mTimer == -1) {
938 mTimer = now;
939 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -0700940 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700941 Thread.sleep(yield ? 200 : 1);
942 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700943 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700944 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700945 }
946 }
947
948 private void execute() {
949 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700950 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700951 try {
952 // Initialize the timer.
953 checkpoint(false);
954
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700955 // Wait for the daemons to stop.
956 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700957 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700958 checkpoint(true);
959 }
960 }
961
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700962 // Clear the previous state.
963 File state = new File("/data/misc/vpn/state");
964 state.delete();
965 if (state.exists()) {
966 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700967 }
Chia-chi Yehc1872732011-12-08 16:51:41 -0800968 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700969 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700970
Chia-chi Yehe9107902011-07-02 01:48:50 -0700971 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700972 boolean restart = false;
973 for (String[] arguments : mArguments) {
974 restart = restart || (arguments != null);
975 }
976 if (!restart) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700977 updateState(DetailedState.DISCONNECTED, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700978 return;
979 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700980 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700981
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700982 // Start the daemon with arguments.
983 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700984 String[] arguments = mArguments[i];
985 if (arguments == null) {
986 continue;
987 }
988
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700989 // Start the daemon.
990 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700991 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700992
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700993 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700994 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700995 checkpoint(true);
996 }
997
998 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700999 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001000 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001001 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001002
1003 // Wait for the socket to connect.
1004 while (true) {
1005 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001006 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001007 break;
1008 } catch (Exception e) {
1009 // ignore
1010 }
1011 checkpoint(true);
1012 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001013 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001014
1015 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001016 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001018 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001019 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001020 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001021 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001022 out.write(bytes.length >> 8);
1023 out.write(bytes.length);
1024 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001025 checkpoint(false);
1026 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001027 out.write(0xFF);
1028 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001029 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001030
1031 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001032 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001033 while (true) {
1034 try {
1035 if (in.read() == -1) {
1036 break;
1037 }
1038 } catch (Exception e) {
1039 // ignore
1040 }
1041 checkpoint(true);
1042 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001043 }
1044
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001045 // Wait for the daemons to create the new state.
1046 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001047 // Check if a running daemon is dead.
1048 for (int i = 0; i < mDaemons.length; ++i) {
1049 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001050 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001051 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001052 }
1053 }
1054 checkpoint(true);
1055 }
1056
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001057 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001058 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001059 if (parameters.length != 6) {
1060 throw new IllegalStateException("Cannot parse the state");
1061 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001063 // Set the interface and the addresses in the config.
1064 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001065
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001066 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001067 // Set the routes if they are not set in the config.
1068 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001069 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001070 }
1071
1072 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001073 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001074 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001075 if (!dnsServers.isEmpty()) {
1076 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1077 }
1078 }
1079
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001080 // Set the search domains if they are not set in the config.
1081 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1082 String searchDomains = parameters[4].trim();
1083 if (!searchDomains.isEmpty()) {
1084 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1085 }
1086 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001087
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001088 // Set the routes.
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001089 long token = Binder.clearCallingIdentity();
1090 try {
1091 mCallback.setMarkedForwarding(mConfig.interfaze);
1092 mCallback.setRoutes(mConfig.interfaze, mConfig.routes);
1093 } finally {
1094 Binder.restoreCallingIdentity(token);
1095 }
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001096
1097 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001098 synchronized (Vpn.this) {
1099 // Check if the thread is interrupted while we are waiting.
1100 checkpoint(false);
1101
Chia-chi Yehe9107902011-07-02 01:48:50 -07001102 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001103 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001104 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001105 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001106
1107 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001108 mInterface = mConfig.interfaze;
Chad Brubakerc2865192013-07-10 14:46:23 -07001109 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001110
1111 token = Binder.clearCallingIdentity();
1112 try {
1113 mCallback.override(mInterface, mConfig.dnsServers, mConfig.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -07001114 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001115 } finally {
1116 Binder.restoreCallingIdentity(token);
1117 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001118
Chad Brubakerc2865192013-07-10 14:46:23 -07001119 // Assign all restircted users to this VPN
1120 // (Legacy VPNs are Owner only)
1121 UserManager mgr = UserManager.get(mContext);
1122 token = Binder.clearCallingIdentity();
1123 try {
1124 for (UserInfo user : mgr.getUsers()) {
1125 if (user.isRestricted()) {
1126 try {
1127 addVpnUserLocked(user.id);
1128 } catch (Exception e) {
1129 Log.wtf(TAG, "Failed to add user " + user.id
1130 + " to owner's VPN");
1131 }
1132 }
1133 }
1134 } finally {
1135 Binder.restoreCallingIdentity(token);
1136 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001137 Log.i(TAG, "Connected!");
Jeff Sharkey899223b2012-08-04 15:24:58 -07001138 updateState(DetailedState.CONNECTED, "execute");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001139 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001140 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001141 Log.i(TAG, "Aborting", e);
Chad Brubakerc2865192013-07-10 14:46:23 -07001142 // make sure the routing is cleared
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001143 try {
1144 mCallback.clearMarkedForwarding(mConfig.interfaze);
1145 } catch (Exception ignored) {
1146 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001147 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001148 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001149 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001150 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001151 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001152 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001153 }
1154 }
1155
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001156 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001157 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1158 updateState(DetailedState.FAILED, "execute");
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001159 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001160 }
1161 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001162
1163 /**
1164 * Monitor the daemons we started, moving to disconnected state if the
1165 * underlying services fail.
1166 */
1167 private void monitorDaemons() {
1168 if (!mNetworkInfo.isConnected()) {
1169 return;
1170 }
1171
1172 try {
1173 while (true) {
1174 Thread.sleep(2000);
1175 for (int i = 0; i < mDaemons.length; i++) {
1176 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1177 return;
1178 }
1179 }
1180 }
1181 } catch (InterruptedException e) {
1182 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1183 } finally {
1184 for (String daemon : mDaemons) {
1185 SystemService.stop(daemon);
1186 }
1187
1188 updateState(DetailedState.DISCONNECTED, "babysit");
1189 }
1190 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001191 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001192}