blob: 7c456aeb2297e150544f10bd0ab100e10ebd05cb [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();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700245 final boolean forwardDns = (mConfig.dnsServers != null &&
246 mConfig.dnsServers.size() != 0);
Chad Brubakerc2865192013-07-10 14:46:23 -0700247 for (int i = 0; i < size; i++) {
248 int user = mVpnUsers.keyAt(i);
Robert Greenwalt69887e82013-09-24 11:05:57 -0700249 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700250 hideNotification(user);
251 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700252
253 mCallback.clearMarkedForwarding(mInterface);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700254 } finally {
255 Binder.restoreCallingIdentity(token);
256 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700257 jniReset(mInterface);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700258 mInterface = null;
Chad Brubakerc2865192013-07-10 14:46:23 -0700259 mVpnUsers = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700260 }
261
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700262 // Revoke the connection or stop LegacyVpnRunner.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700263 if (mConnection != null) {
264 try {
265 mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
266 Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
267 } catch (Exception e) {
268 // ignore
269 }
270 mContext.unbindService(mConnection);
271 mConnection = null;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700272 } else if (mLegacyVpnRunner != null) {
273 mLegacyVpnRunner.exit();
274 mLegacyVpnRunner = null;
275 }
276
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700277 Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
278 mPackage = newPackage;
Chad Brubakerc2865192013-07-10 14:46:23 -0700279 mConfig = null;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700280 updateState(DetailedState.IDLE, "prepare");
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700281 return true;
Chia-chi Yehe9107902011-07-02 01:48:50 -0700282 }
283
284 /**
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700285 * Protect a socket from routing changes by binding it to the given
286 * interface. The socket is NOT closed by this method.
287 *
288 * @param socket The socket to be bound.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700289 * @param interfaze The name of the interface.
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700290 */
291 public void protect(ParcelFileDescriptor socket, String interfaze) throws Exception {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700292
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700293 PackageManager pm = mContext.getPackageManager();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700294 int appUid = pm.getPackageUid(mPackage, mUserId);
295 if (Binder.getCallingUid() != appUid) {
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700296 throw new SecurityException("Unauthorized Caller");
297 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700298 // protect the socket from routing rules
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700299 final long token = Binder.clearCallingIdentity();
300 try {
301 mCallback.protect(socket);
302 } finally {
303 Binder.restoreCallingIdentity(token);
304 }
Chad Brubakerc2865192013-07-10 14:46:23 -0700305 // bind the socket to the interface
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700306 jniProtect(socket.getFd(), interfaze);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700307
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700308 }
309
310 /**
Chia-chi Yehe9107902011-07-02 01:48:50 -0700311 * Establish a VPN network and return the file descriptor of the VPN
312 * interface. This methods returns {@code null} if the application is
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700313 * revoked or not prepared.
Chia-chi Yehe9107902011-07-02 01:48:50 -0700314 *
315 * @param config The parameters to configure the network.
316 * @return The file descriptor of the VPN interface.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700317 */
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700318 public synchronized ParcelFileDescriptor establish(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700319 // Check if the caller is already prepared.
Chad Brubakerc2865192013-07-10 14:46:23 -0700320 UserManager mgr = UserManager.get(mContext);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700321 PackageManager pm = mContext.getPackageManager();
322 ApplicationInfo app = null;
323 try {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700324 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
325 if (Binder.getCallingUid() != app.uid) {
326 return null;
327 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700328 } catch (Exception e) {
Chia-chi Yeh7b0b8342011-06-17 14:34:11 -0700329 return null;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700330 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700331 // Check if the service is properly declared.
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700332 Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
333 intent.setClassName(mPackage, config.user);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700334 long token = Binder.clearCallingIdentity();
335 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700336 // Restricted users are not allowed to create VPNs, they are tied to Owner
337 UserInfo user = mgr.getUserInfo(mUserId);
338 if (user.isRestricted()) {
339 throw new SecurityException("Restricted users cannot establish VPNs");
340 }
341
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700342 ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
343 null, 0, mUserId);
344 if (info == null) {
345 throw new SecurityException("Cannot find " + config.user);
346 }
347 if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
348 throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
349 }
350 } catch (RemoteException e) {
351 throw new SecurityException("Cannot find " + config.user);
352 } finally {
353 Binder.restoreCallingIdentity(token);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700354 }
Chia-chi Yehfcc1b412011-08-03 15:39:59 -0700355
Chia-chi Yehe9107902011-07-02 01:48:50 -0700356 // Configure the interface. Abort if any of these steps fails.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700357 ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700358 try {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700359 updateState(DetailedState.CONNECTING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700360 String interfaze = jniGetName(tun.getFd());
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700361
Chad Brubakerc2865192013-07-10 14:46:23 -0700362 // TEMP use the old jni calls until there is support for netd address setting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700363 StringBuilder builder = new StringBuilder();
364 for (LinkAddress address : config.addresses) {
365 builder.append(" " + address);
366 }
367 if (jniSetAddresses(interfaze, builder.toString()) < 1) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700368 throw new IllegalArgumentException("At least one address must be specified");
369 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700370 Connection connection = new Connection();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700371 if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
372 new UserHandle(mUserId))) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700373 throw new IllegalStateException("Cannot bind " + config.user);
374 }
375 if (mConnection != null) {
376 mContext.unbindService(mConnection);
377 }
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700378 if (mInterface != null && !mInterface.equals(interfaze)) {
379 jniReset(mInterface);
Chia-chi Yehf4e3bf82011-06-30 12:33:17 -0700380 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700381 mConnection = connection;
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700382 mInterface = interfaze;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700383
384 // Fill more values.
385 config.user = mPackage;
386 config.interfaze = mInterface;
Chad Brubakerc2865192013-07-10 14:46:23 -0700387 config.startTime = SystemClock.elapsedRealtime();
388 mConfig = config;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700389 // Set up forwarding and DNS rules.
Chad Brubakerc2865192013-07-10 14:46:23 -0700390 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700391 token = Binder.clearCallingIdentity();
392 try {
393 mCallback.setMarkedForwarding(mInterface);
394 mCallback.setRoutes(interfaze, config.routes);
395 mCallback.override(mInterface, config.dnsServers, config.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -0700396 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700397
398 } finally {
399 Binder.restoreCallingIdentity(token);
400 }
401
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700402 } catch (RuntimeException e) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700403 updateState(DetailedState.FAILED, "establish");
Jeff Sharkey065b2992012-08-05 14:16:48 -0700404 IoUtils.closeQuietly(tun);
Chad Brubakerc2865192013-07-10 14:46:23 -0700405 // make sure marked forwarding is cleared if it was set
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700406 try {
407 mCallback.clearMarkedForwarding(mInterface);
408 } catch (Exception ingored) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700409 // ignored
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700410 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700411 throw e;
412 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700413 Log.i(TAG, "Established by " + config.user + " on " + mInterface);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700414
Chia-chi Yeh8909b102011-07-01 01:09:42 -0700415
Chad Brubakerc2865192013-07-10 14:46:23 -0700416 // If we are owner assign all Restricted Users to this VPN
417 if (mUserId == UserHandle.USER_OWNER) {
418 token = Binder.clearCallingIdentity();
419 try {
420 for (UserInfo user : mgr.getUsers()) {
421 if (user.isRestricted()) {
422 try {
423 addVpnUserLocked(user.id);
424 } catch (Exception e) {
425 Log.wtf(TAG, "Failed to add user " + user.id + " to owner's VPN");
426 }
427 }
428 }
429 } finally {
430 Binder.restoreCallingIdentity(token);
431 }
432 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700433 // TODO: ensure that contract class eventually marks as connected
434 updateState(DetailedState.AUTHENTICATING, "establish");
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700435 return tun;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700436 }
437
Chad Brubakerc2865192013-07-10 14:46:23 -0700438 private boolean isRunningLocked() {
439 return mVpnUsers != null;
440 }
441
442 private void addVpnUserLocked(int user) {
443 enforceControlPermission();
444
445 if (!isRunningLocked()) {
446 throw new IllegalStateException("VPN is not active");
447 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700448
449 final boolean forwardDns = (mConfig.dnsServers != null &&
450 mConfig.dnsServers.size() != 0);
451
Chad Brubakerc2865192013-07-10 14:46:23 -0700452 // add the user
Robert Greenwalt69887e82013-09-24 11:05:57 -0700453 mCallback.addUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700454 mVpnUsers.put(user, true);
455
456 // show the notification
457 if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
458 // Load everything for the user's notification
459 PackageManager pm = mContext.getPackageManager();
460 ApplicationInfo app = null;
461 try {
462 app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
463 } catch (RemoteException e) {
464 throw new IllegalStateException("Invalid application");
465 }
466 String label = app.loadLabel(pm).toString();
467 // Load the icon and convert it into a bitmap.
468 Drawable icon = app.loadIcon(pm);
469 Bitmap bitmap = null;
470 if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
471 int width = mContext.getResources().getDimensionPixelSize(
472 android.R.dimen.notification_large_icon_width);
473 int height = mContext.getResources().getDimensionPixelSize(
474 android.R.dimen.notification_large_icon_height);
475 icon.setBounds(0, 0, width, height);
476 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
477 Canvas c = new Canvas(bitmap);
478 icon.draw(c);
479 c.setBitmap(null);
480 }
481 showNotification(label, bitmap, user);
482 } else {
483 showNotification(null, null, user);
484 }
485 }
486
487 private void removeVpnUserLocked(int user) {
488 enforceControlPermission();
489
490 if (!isRunningLocked()) {
491 throw new IllegalStateException("VPN is not active");
492 }
Robert Greenwalt69887e82013-09-24 11:05:57 -0700493 final boolean forwardDns = (mConfig.dnsServers != null &&
494 mConfig.dnsServers.size() != 0);
495 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700496 mVpnUsers.delete(user);
497 hideNotification(user);
498 }
499
500 private void onUserAdded(int userId) {
501 // If the user is restricted tie them to the owner's VPN
502 synchronized(Vpn.this) {
503 UserManager mgr = UserManager.get(mContext);
504 UserInfo user = mgr.getUserInfo(userId);
505 if (user.isRestricted()) {
506 try {
507 addVpnUserLocked(userId);
508 } catch (Exception e) {
509 Log.wtf(TAG, "Failed to add restricted user to owner", e);
510 }
511 }
512 }
513 }
514
515 private void onUserRemoved(int userId) {
516 // clean up if restricted
517 synchronized(Vpn.this) {
518 UserManager mgr = UserManager.get(mContext);
519 UserInfo user = mgr.getUserInfo(userId);
520 if (user.isRestricted()) {
521 try {
522 removeVpnUserLocked(userId);
523 } catch (Exception e) {
524 Log.wtf(TAG, "Failed to remove restricted user to owner", e);
525 }
526 }
527 }
528 }
529
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700530 /**
531 * Return the configuration of the currently running VPN.
532 */
533 public VpnConfig getVpnConfig() {
534 enforceControlPermission();
535 return mConfig;
536 }
537
Jeff Sharkey899223b2012-08-04 15:24:58 -0700538 @Deprecated
539 public synchronized void interfaceStatusChanged(String iface, boolean up) {
540 try {
541 mObserver.interfaceStatusChanged(iface, up);
542 } catch (RemoteException e) {
543 // ignored; target is local
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700544 }
545 }
546
Jeff Sharkey899223b2012-08-04 15:24:58 -0700547 private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
548 @Override
549 public void interfaceStatusChanged(String interfaze, boolean up) {
550 synchronized (Vpn.this) {
551 if (!up && mLegacyVpnRunner != null) {
552 mLegacyVpnRunner.check(interfaze);
553 }
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700554 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700555 }
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700556
Jeff Sharkey899223b2012-08-04 15:24:58 -0700557 @Override
558 public void interfaceRemoved(String interfaze) {
559 synchronized (Vpn.this) {
560 if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
561 final long token = Binder.clearCallingIdentity();
562 try {
Chad Brubakerc2865192013-07-10 14:46:23 -0700563 final int size = mVpnUsers.size();
Robert Greenwalt69887e82013-09-24 11:05:57 -0700564 final boolean forwardDns = (mConfig.dnsServers != null &&
565 mConfig.dnsServers.size() != 0);
Chad Brubakerc2865192013-07-10 14:46:23 -0700566 for (int i = 0; i < size; i++) {
567 int user = mVpnUsers.keyAt(i);
Robert Greenwalt69887e82013-09-24 11:05:57 -0700568 mCallback.clearUserForwarding(mInterface, user, forwardDns);
Chad Brubakerc2865192013-07-10 14:46:23 -0700569 hideNotification(user);
570 }
571 mVpnUsers = null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700572 mCallback.clearMarkedForwarding(mInterface);
573
Jeff Sharkey899223b2012-08-04 15:24:58 -0700574 mCallback.restore();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700575 } finally {
576 Binder.restoreCallingIdentity(token);
577 }
578 mInterface = null;
579 if (mConnection != null) {
580 mContext.unbindService(mConnection);
581 mConnection = null;
582 updateState(DetailedState.DISCONNECTED, "interfaceRemoved");
583 } else if (mLegacyVpnRunner != null) {
584 mLegacyVpnRunner.exit();
585 mLegacyVpnRunner = null;
586 }
587 }
588 }
589 }
590 };
Haoyu Baidb3c8672012-06-20 14:29:57 -0700591
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700592 private void enforceControlPermission() {
593 // System user is allowed to control VPN.
594 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
595 return;
596 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700597 int appId = UserHandle.getAppId(Binder.getCallingUid());
598 final long token = Binder.clearCallingIdentity();
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700599 try {
600 // System dialogs are also allowed to control VPN.
601 PackageManager pm = mContext.getPackageManager();
602 ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700603 if (appId == app.uid) {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700604 return;
605 }
606 } catch (Exception e) {
607 // ignore
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700608 } finally {
609 Binder.restoreCallingIdentity(token);
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700610 }
611
612 throw new SecurityException("Unauthorized Caller");
613 }
614
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700615 private class Connection implements ServiceConnection {
616 private IBinder mService;
617
618 @Override
619 public void onServiceConnected(ComponentName name, IBinder service) {
620 mService = service;
621 }
622
623 @Override
624 public void onServiceDisconnected(ComponentName name) {
625 mService = null;
626 }
627 }
628
Chad Brubakerc2865192013-07-10 14:46:23 -0700629 private void showNotification(String label, Bitmap icon, int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700630 if (!mEnableNotif) return;
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -0700631 mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700632
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700633 NotificationManager nm = (NotificationManager)
634 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
635
636 if (nm != null) {
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700637 String title = (label == null) ? mContext.getString(R.string.vpn_title) :
638 mContext.getString(R.string.vpn_title_long, label);
Chad Brubakerc2865192013-07-10 14:46:23 -0700639 String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
640 mContext.getString(R.string.vpn_text_long, mConfig.session);
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700641
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700642 Notification notification = new Notification.Builder(mContext)
643 .setSmallIcon(R.drawable.vpn_connected)
Chia-chi Yeha4b87b52011-06-30 23:21:55 -0700644 .setLargeIcon(icon)
645 .setContentTitle(title)
Chia-chi Yehf8905fd2011-06-14 16:35:02 -0700646 .setContentText(text)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700647 .setContentIntent(mStatusIntent)
Chia-chi Yeh50fe7092012-01-11 14:26:24 -0800648 .setDefaults(0)
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700649 .setOngoing(true)
Jeff Sharkey899223b2012-08-04 15:24:58 -0700650 .build();
Chad Brubakerc2865192013-07-10 14:46:23 -0700651 nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700652 }
653 }
654
Chad Brubakerc2865192013-07-10 14:46:23 -0700655 private void hideNotification(int user) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700656 if (!mEnableNotif) return;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700657 mStatusIntent = null;
658
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700659 NotificationManager nm = (NotificationManager)
660 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
661
662 if (nm != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700663 nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700664 }
665 }
666
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700667 private native int jniCreate(int mtu);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700668 private native String jniGetName(int tun);
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700669 private native int jniSetAddresses(String interfaze, String addresses);
670 private native int jniSetRoutes(String interfaze, String routes);
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -0700671 private native void jniReset(String interfaze);
672 private native int jniCheck(String interfaze);
673 private native void jniProtect(int socket, String interfaze);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700674
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900675 private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
676 for (RouteInfo route : prop.getAllRoutes()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700677 // Currently legacy VPN only works on IPv4.
678 if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900679 return route;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700680 }
681 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700682
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900683 throw new IllegalStateException("Unable to find IPv4 default gateway");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700684 }
685
686 /**
687 * Start legacy VPN, controlling native daemons as needed. Creates a
688 * secondary thread to perform connection work, returning quickly.
689 */
690 public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -0800691 enforceControlPermission();
Kenny Rootb9594ce2013-02-14 10:18:38 -0800692 if (!keyStore.isUnlocked()) {
Jeff Sharkey82f85212012-08-24 11:17:25 -0700693 throw new IllegalStateException("KeyStore isn't unlocked");
694 }
695
Lorenzo Colitti41fb98c2013-06-28 17:26:21 +0900696 final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
697 final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
698 final String iface = ipv4DefaultRoute.getInterface();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700699
700 // Load certificates.
701 String privateKey = "";
702 String userCert = "";
703 String caCert = "";
704 String serverCert = "";
705 if (!profile.ipsecUserCert.isEmpty()) {
706 privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
707 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700708 userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700709 }
710 if (!profile.ipsecCaCert.isEmpty()) {
711 byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700712 caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700713 }
714 if (!profile.ipsecServerCert.isEmpty()) {
715 byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
Elliott Hughesd396a442013-06-28 16:24:48 -0700716 serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700717 }
718 if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
719 throw new IllegalStateException("Cannot load credentials");
720 }
721
722 // Prepare arguments for racoon.
723 String[] racoon = null;
724 switch (profile.type) {
725 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
726 racoon = new String[] {
727 iface, profile.server, "udppsk", profile.ipsecIdentifier,
728 profile.ipsecSecret, "1701",
729 };
730 break;
731 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
732 racoon = new String[] {
733 iface, profile.server, "udprsa", privateKey, userCert,
734 caCert, serverCert, "1701",
735 };
736 break;
737 case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
738 racoon = new String[] {
739 iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
740 profile.ipsecSecret, profile.username, profile.password, "", gateway,
741 };
742 break;
743 case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
744 racoon = new String[] {
745 iface, profile.server, "xauthrsa", privateKey, userCert,
746 caCert, serverCert, profile.username, profile.password, "", gateway,
747 };
748 break;
749 case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
750 racoon = new String[] {
751 iface, profile.server, "hybridrsa",
752 caCert, serverCert, profile.username, profile.password, "", gateway,
753 };
754 break;
755 }
756
757 // Prepare arguments for mtpd.
758 String[] mtpd = null;
759 switch (profile.type) {
760 case VpnProfile.TYPE_PPTP:
761 mtpd = new String[] {
762 iface, "pptp", profile.server, "1723",
763 "name", profile.username, "password", profile.password,
764 "linkname", "vpn", "refuse-eap", "nodefaultroute",
765 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
766 (profile.mppe ? "+mppe" : "nomppe"),
767 };
768 break;
769 case VpnProfile.TYPE_L2TP_IPSEC_PSK:
770 case VpnProfile.TYPE_L2TP_IPSEC_RSA:
771 mtpd = new String[] {
772 iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
773 "name", profile.username, "password", profile.password,
774 "linkname", "vpn", "refuse-eap", "nodefaultroute",
775 "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
776 };
777 break;
778 }
779
780 VpnConfig config = new VpnConfig();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700781 config.legacy = true;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700782 config.user = profile.key;
783 config.interfaze = iface;
784 config.session = profile.name;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700785
786 config.addLegacyRoutes(profile.routes);
Jeff Sharkey82f85212012-08-24 11:17:25 -0700787 if (!profile.dnsServers.isEmpty()) {
788 config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
789 }
790 if (!profile.searchDomains.isEmpty()) {
791 config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
792 }
Jeff Sharkey82f85212012-08-24 11:17:25 -0700793 startLegacyVpn(config, racoon, mtpd);
794 }
795
796 private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
797 stopLegacyVpn();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700798
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700799 // Prepare for the new request. This also checks the caller.
800 prepare(null, VpnConfig.LEGACY_VPN);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700801 updateState(DetailedState.CONNECTING, "startLegacyVpn");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700802
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700803 // Start a new LegacyVpnRunner and we are done!
Chia-chi Yeh100155a2011-07-03 16:52:38 -0700804 mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
805 mLegacyVpnRunner.start();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700806 }
807
Jeff Sharkey899223b2012-08-04 15:24:58 -0700808 public synchronized void stopLegacyVpn() {
809 if (mLegacyVpnRunner != null) {
810 mLegacyVpnRunner.exit();
811 mLegacyVpnRunner = null;
812
813 synchronized (LegacyVpnRunner.TAG) {
814 // wait for old thread to completely finish before spinning up
815 // new instance, otherwise state updates can be out of order.
816 }
817 }
818 }
819
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700820 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700821 * Return the information of the current ongoing legacy VPN.
822 */
823 public synchronized LegacyVpnInfo getLegacyVpnInfo() {
Chia-chi Yehdadc8572012-06-08 13:05:58 -0700824 // Check if the caller is authorized.
825 enforceControlPermission();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700826 if (mLegacyVpnRunner == null) return null;
827
828 final LegacyVpnInfo info = new LegacyVpnInfo();
Chad Brubakerc2865192013-07-10 14:46:23 -0700829 info.key = mConfig.user;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700830 info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
831 if (mNetworkInfo.isConnected()) {
832 info.intent = mStatusIntent;
833 }
834 return info;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700835 }
836
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700837 public VpnConfig getLegacyVpnConfig() {
838 if (mLegacyVpnRunner != null) {
Chad Brubakerc2865192013-07-10 14:46:23 -0700839 return mConfig;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700840 } else {
841 return null;
842 }
843 }
844
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700845 /**
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700846 * Bringing up a VPN connection takes time, and that is all this thread
847 * does. Here we have plenty of time. The only thing we need to take
848 * care of is responding to interruptions as soon as possible. Otherwise
849 * requests will be piled up. This can be done in a Handler as a state
850 * machine, but it is much easier to read in the current form.
851 */
852 private class LegacyVpnRunner extends Thread {
853 private static final String TAG = "LegacyVpnRunner";
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700854
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700855 private final String[] mDaemons;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700856 private final String[][] mArguments;
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700857 private final LocalSocket[] mSockets;
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700858 private final String mOuterInterface;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700859 private final AtomicInteger mOuterConnection =
860 new AtomicInteger(ConnectivityManager.TYPE_NONE);
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700861
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700862 private long mTimer = -1;
863
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700864 /**
865 * Watch for the outer connection (passing in the constructor) going away.
866 */
867 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
868 @Override
869 public void onReceive(Context context, Intent intent) {
Jeff Sharkey57666932013-04-30 17:01:57 -0700870 if (!mEnableTeardown) return;
871
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700872 if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
873 if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
874 ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
875 NetworkInfo info = (NetworkInfo)intent.getExtra(
876 ConnectivityManager.EXTRA_NETWORK_INFO);
877 if (info != null && !info.isConnectedOrConnecting()) {
878 try {
879 mObserver.interfaceStatusChanged(mOuterInterface, false);
880 } catch (RemoteException e) {}
881 }
882 }
883 }
884 }
885 };
886
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700887 public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700888 super(TAG);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700889 mConfig = config;
890 mDaemons = new String[] {"racoon", "mtpd"};
Jeff Sharkey899223b2012-08-04 15:24:58 -0700891 // TODO: clear arguments from memory once launched
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700892 mArguments = new String[][] {racoon, mtpd};
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700893 mSockets = new LocalSocket[mDaemons.length];
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700894
895 // This is the interface which VPN is running on,
896 // mConfig.interfaze will change to point to OUR
897 // internal interface soon. TODO - add inner/outer to mconfig
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700898 // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700899 // we will leave the VPN up. We should check that it's still there/connected after
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700900 // registering
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700901 mOuterInterface = mConfig.interfaze;
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700902
903 try {
904 mOuterConnection.set(
905 mConnService.findConnectionTypeForIface(mOuterInterface));
906 } catch (Exception e) {
907 mOuterConnection.set(ConnectivityManager.TYPE_NONE);
908 }
909
910 IntentFilter filter = new IntentFilter();
911 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
912 mContext.registerReceiver(mBroadcastReceiver, filter);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700913 }
914
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700915 public void check(String interfaze) {
Robert Greenwalt53c04bd2012-10-12 17:02:45 -0700916 if (interfaze.equals(mOuterInterface)) {
Chia-chi Yehaa1727f2011-07-14 18:55:33 -0700917 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
918 exit();
919 }
920 }
921
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700922 public void exit() {
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700923 // We assume that everything is reset after stopping the daemons.
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700924 interrupt();
Chia-chi Yeh5317f032011-08-22 13:09:49 -0700925 for (LocalSocket socket : mSockets) {
Jeff Sharkey065b2992012-08-05 14:16:48 -0700926 IoUtils.closeQuietly(socket);
Chia-chi Yeh41d16852011-07-01 02:12:06 -0700927 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700928 updateState(DetailedState.DISCONNECTED, "exit");
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700929 try {
930 mContext.unregisterReceiver(mBroadcastReceiver);
931 } catch (IllegalArgumentException e) {}
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700932 }
933
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700934 @Override
935 public void run() {
936 // Wait for the previous thread since it has been interrupted.
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700937 Log.v(TAG, "Waiting");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700938 synchronized (TAG) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700939 Log.v(TAG, "Executing");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700940 execute();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700941 monitorDaemons();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700942 }
943 }
944
945 private void checkpoint(boolean yield) throws InterruptedException {
946 long now = SystemClock.elapsedRealtime();
947 if (mTimer == -1) {
948 mTimer = now;
949 Thread.sleep(1);
Chia-chi Yeh7ef86112011-07-22 15:46:52 -0700950 } else if (now - mTimer <= 60000) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700951 Thread.sleep(yield ? 200 : 1);
952 } else {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700953 updateState(DetailedState.FAILED, "checkpoint");
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700954 throw new IllegalStateException("Time is up");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700955 }
956 }
957
958 private void execute() {
959 // Catch all exceptions so we can clean up few things.
Jeff Sharkey899223b2012-08-04 15:24:58 -0700960 boolean initFinished = false;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700961 try {
962 // Initialize the timer.
963 checkpoint(false);
964
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700965 // Wait for the daemons to stop.
966 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -0700967 while (!SystemService.isStopped(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700968 checkpoint(true);
969 }
970 }
971
Chia-chi Yeh97a61562011-07-14 15:05:05 -0700972 // Clear the previous state.
973 File state = new File("/data/misc/vpn/state");
974 state.delete();
975 if (state.exists()) {
976 throw new IllegalStateException("Cannot delete the state");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700977 }
Chia-chi Yehc1872732011-12-08 16:51:41 -0800978 new File("/data/misc/vpn/abort").delete();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700979 initFinished = true;
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700980
Chia-chi Yehe9107902011-07-02 01:48:50 -0700981 // Check if we need to restart any of the daemons.
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700982 boolean restart = false;
983 for (String[] arguments : mArguments) {
984 restart = restart || (arguments != null);
985 }
986 if (!restart) {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700987 updateState(DetailedState.DISCONNECTED, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700988 return;
989 }
Jeff Sharkey899223b2012-08-04 15:24:58 -0700990 updateState(DetailedState.CONNECTING, "execute");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700991
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700992 // Start the daemon with arguments.
993 for (int i = 0; i < mDaemons.length; ++i) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -0700994 String[] arguments = mArguments[i];
995 if (arguments == null) {
996 continue;
997 }
998
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -0700999 // Start the daemon.
1000 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001001 SystemService.start(daemon);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001002
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001003 // Wait for the daemon to start.
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001004 while (!SystemService.isRunning(daemon)) {
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001005 checkpoint(true);
1006 }
1007
1008 // Create the control socket.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001009 mSockets[i] = new LocalSocket();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001010 LocalSocketAddress address = new LocalSocketAddress(
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001011 daemon, LocalSocketAddress.Namespace.RESERVED);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001012
1013 // Wait for the socket to connect.
1014 while (true) {
1015 try {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001016 mSockets[i].connect(address);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001017 break;
1018 } catch (Exception e) {
1019 // ignore
1020 }
1021 checkpoint(true);
1022 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001023 mSockets[i].setSoTimeout(500);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001024
1025 // Send over the arguments.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001026 OutputStream out = mSockets[i].getOutputStream();
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001027 for (String argument : arguments) {
Elliott Hughesd396a442013-06-28 16:24:48 -07001028 byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001029 if (bytes.length >= 0xFFFF) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001030 throw new IllegalArgumentException("Argument is too large");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001031 }
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001032 out.write(bytes.length >> 8);
1033 out.write(bytes.length);
1034 out.write(bytes);
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001035 checkpoint(false);
1036 }
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001037 out.write(0xFF);
1038 out.write(0xFF);
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001039 out.flush();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001040
1041 // Wait for End-of-File.
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001042 InputStream in = mSockets[i].getInputStream();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001043 while (true) {
1044 try {
1045 if (in.read() == -1) {
1046 break;
1047 }
1048 } catch (Exception e) {
1049 // ignore
1050 }
1051 checkpoint(true);
1052 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001053 }
1054
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001055 // Wait for the daemons to create the new state.
1056 while (!state.exists()) {
Chia-chi Yeh1f7746b2011-07-01 00:29:06 -07001057 // Check if a running daemon is dead.
1058 for (int i = 0; i < mDaemons.length; ++i) {
1059 String daemon = mDaemons[i];
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001060 if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001061 throw new IllegalStateException(daemon + " is dead");
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001062 }
1063 }
1064 checkpoint(true);
1065 }
1066
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001067 // Now we are connected. Read and parse the new state.
Chia-chi Yehc1bac3a2011-12-16 15:00:31 -08001068 String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001069 if (parameters.length != 6) {
1070 throw new IllegalStateException("Cannot parse the state");
1071 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001072
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001073 // Set the interface and the addresses in the config.
1074 mConfig.interfaze = parameters[0].trim();
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001075
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001076 mConfig.addLegacyAddresses(parameters[1]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001077 // Set the routes if they are not set in the config.
1078 if (mConfig.routes == null || mConfig.routes.isEmpty()) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001079 mConfig.addLegacyRoutes(parameters[2]);
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001080 }
1081
1082 // Set the DNS servers if they are not set in the config.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001083 if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001084 String dnsServers = parameters[3].trim();
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001085 if (!dnsServers.isEmpty()) {
1086 mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1087 }
1088 }
1089
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001090 // Set the search domains if they are not set in the config.
1091 if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1092 String searchDomains = parameters[4].trim();
1093 if (!searchDomains.isEmpty()) {
1094 mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1095 }
1096 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001097
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001098 // Set the routes.
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001099 long token = Binder.clearCallingIdentity();
1100 try {
1101 mCallback.setMarkedForwarding(mConfig.interfaze);
1102 mCallback.setRoutes(mConfig.interfaze, mConfig.routes);
1103 } finally {
1104 Binder.restoreCallingIdentity(token);
1105 }
Chia-chi Yeh97a61562011-07-14 15:05:05 -07001106
1107 // Here is the last step and it must be done synchronously.
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001108 synchronized (Vpn.this) {
1109 // Check if the thread is interrupted while we are waiting.
1110 checkpoint(false);
1111
Chia-chi Yehe9107902011-07-02 01:48:50 -07001112 // Check if the interface is gone while we are waiting.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001113 if (jniCheck(mConfig.interfaze) == 0) {
Chia-chi Yeh34e78132011-07-03 03:07:07 -07001114 throw new IllegalStateException(mConfig.interfaze + " is gone");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001115 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001116
1117 // Now INetworkManagementEventObserver is watching our back.
Chia-chi Yehc2b8aa02011-07-03 18:00:47 -07001118 mInterface = mConfig.interfaze;
Chad Brubakerc2865192013-07-10 14:46:23 -07001119 mVpnUsers = new SparseBooleanArray();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001120
1121 token = Binder.clearCallingIdentity();
1122 try {
1123 mCallback.override(mInterface, mConfig.dnsServers, mConfig.searchDomains);
Chad Brubakerc2865192013-07-10 14:46:23 -07001124 addVpnUserLocked(mUserId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001125 } finally {
1126 Binder.restoreCallingIdentity(token);
1127 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001128
Chad Brubakerc2865192013-07-10 14:46:23 -07001129 // Assign all restircted users to this VPN
1130 // (Legacy VPNs are Owner only)
1131 UserManager mgr = UserManager.get(mContext);
1132 token = Binder.clearCallingIdentity();
1133 try {
1134 for (UserInfo user : mgr.getUsers()) {
1135 if (user.isRestricted()) {
1136 try {
1137 addVpnUserLocked(user.id);
1138 } catch (Exception e) {
1139 Log.wtf(TAG, "Failed to add user " + user.id
1140 + " to owner's VPN");
1141 }
1142 }
1143 }
1144 } finally {
1145 Binder.restoreCallingIdentity(token);
1146 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001147 Log.i(TAG, "Connected!");
Jeff Sharkey899223b2012-08-04 15:24:58 -07001148 updateState(DetailedState.CONNECTED, "execute");
Chia-chi Yeh41d16852011-07-01 02:12:06 -07001149 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001150 } catch (Exception e) {
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001151 Log.i(TAG, "Aborting", e);
Chad Brubakerc2865192013-07-10 14:46:23 -07001152 // make sure the routing is cleared
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001153 try {
1154 mCallback.clearMarkedForwarding(mConfig.interfaze);
1155 } catch (Exception ignored) {
1156 }
Chia-chi Yehe9107902011-07-02 01:48:50 -07001157 exit();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001158 } finally {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001159 // Kill the daemons if they fail to stop.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001160 if (!initFinished) {
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001161 for (String daemon : mDaemons) {
Jeff Sharkey088f29f2012-08-05 14:55:04 -07001162 SystemService.stop(daemon);
Chia-chi Yeh5317f032011-08-22 13:09:49 -07001163 }
1164 }
1165
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001166 // Do not leave an unstable state.
Jeff Sharkey899223b2012-08-04 15:24:58 -07001167 if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1168 updateState(DetailedState.FAILED, "execute");
Chia-chi Yeh2e467642011-07-04 03:23:12 -07001169 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001170 }
1171 }
Jeff Sharkey899223b2012-08-04 15:24:58 -07001172
1173 /**
1174 * Monitor the daemons we started, moving to disconnected state if the
1175 * underlying services fail.
1176 */
1177 private void monitorDaemons() {
1178 if (!mNetworkInfo.isConnected()) {
1179 return;
1180 }
1181
1182 try {
1183 while (true) {
1184 Thread.sleep(2000);
1185 for (int i = 0; i < mDaemons.length; i++) {
1186 if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1187 return;
1188 }
1189 }
1190 }
1191 } catch (InterruptedException e) {
1192 Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1193 } finally {
1194 for (String daemon : mDaemons) {
1195 SystemService.stop(daemon);
1196 }
1197
1198 updateState(DetailedState.DISCONNECTED, "babysit");
1199 }
1200 }
Chia-chi Yeh85a7ce02011-06-29 16:05:58 -07001201 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07001202}