Vpn.java revision 030a6b923400eada46220343b5e9681cd0a191b7
1/*
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
19import static android.Manifest.permission.BIND_VPN_SERVICE;
20
21import android.app.AppGlobals;
22import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.ServiceConnection;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.content.pm.UserInfo;
36import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.drawable.Drawable;
39import android.net.BaseNetworkStateTracker;
40import android.net.ConnectivityManager;
41import android.net.IConnectivityManager;
42import android.net.INetworkManagementEventObserver;
43import android.net.LinkAddress;
44import android.net.LinkProperties;
45import android.net.LocalSocket;
46import android.net.LocalSocketAddress;
47import android.net.NetworkAgent;
48import android.net.NetworkCapabilities;
49import android.net.NetworkInfo;
50import android.net.NetworkInfo.DetailedState;
51import android.net.NetworkMisc;
52import android.net.NetworkUtils;
53import android.net.RouteInfo;
54import android.net.UidRange;
55import android.os.Binder;
56import android.os.FileUtils;
57import android.os.IBinder;
58import android.os.INetworkManagementService;
59import android.os.Looper;
60import android.os.Parcel;
61import android.os.ParcelFileDescriptor;
62import android.os.Process;
63import android.os.RemoteException;
64import android.os.SystemClock;
65import android.os.SystemService;
66import android.os.UserHandle;
67import android.os.UserManager;
68import android.security.Credentials;
69import android.security.KeyStore;
70import android.util.Log;
71import android.util.SparseBooleanArray;
72
73import com.android.internal.annotations.GuardedBy;
74import com.android.internal.R;
75import com.android.internal.net.LegacyVpnInfo;
76import com.android.internal.net.VpnConfig;
77import com.android.internal.net.VpnProfile;
78import com.android.server.net.BaseNetworkObserver;
79
80import java.io.File;
81import java.io.IOException;
82import java.io.InputStream;
83import java.io.OutputStream;
84import java.net.InetAddress;
85import java.net.Inet4Address;
86import java.nio.charset.StandardCharsets;
87import java.util.ArrayList;
88import java.util.Arrays;
89import java.util.List;
90import java.util.concurrent.atomic.AtomicInteger;
91
92import libcore.io.IoUtils;
93
94/**
95 * @hide
96 */
97public class Vpn {
98    private static final String NETWORKTYPE = "VPN";
99    private static final String TAG = "Vpn";
100    private static final boolean LOGD = true;
101
102    // TODO: create separate trackers for each unique VPN to support
103    // automated reconnection
104
105    private Context mContext;
106    private NetworkInfo mNetworkInfo;
107    private String mPackage;
108    private int mOwnerUID;
109    private String mInterface;
110    private Connection mConnection;
111    private LegacyVpnRunner mLegacyVpnRunner;
112    private PendingIntent mStatusIntent;
113    private volatile boolean mEnableNotif = true;
114    private volatile boolean mEnableTeardown = true;
115    private final IConnectivityManager mConnService;
116    private final INetworkManagementService mNetd;
117    private VpnConfig mConfig;
118    private NetworkAgent mNetworkAgent;
119    private final Looper mLooper;
120    private final NetworkCapabilities mNetworkCapabilities;
121
122    /* list of users using this VPN. */
123    @GuardedBy("this")
124    private List<UidRange> mVpnUsers = null;
125    private BroadcastReceiver mUserIntentReceiver = null;
126
127    private final int mUserId;
128
129    public Vpn(Looper looper, Context context, INetworkManagementService netService,
130            IConnectivityManager connService, int userId) {
131        mContext = context;
132        mNetd = netService;
133        mConnService = connService;
134        mUserId = userId;
135        mLooper = looper;
136
137        mPackage = VpnConfig.LEGACY_VPN;
138        mOwnerUID = getAppUid(mPackage);
139
140        try {
141            netService.registerObserver(mObserver);
142        } catch (RemoteException e) {
143            Log.wtf(TAG, "Problem registering observer", e);
144        }
145        if (userId == UserHandle.USER_OWNER) {
146            // Owner's VPN also needs to handle restricted users
147            mUserIntentReceiver = new BroadcastReceiver() {
148                @Override
149                public void onReceive(Context context, Intent intent) {
150                    final String action = intent.getAction();
151                    final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
152                            UserHandle.USER_NULL);
153                    if (userId == UserHandle.USER_NULL) return;
154
155                    if (Intent.ACTION_USER_ADDED.equals(action)) {
156                        onUserAdded(userId);
157                    } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
158                        onUserRemoved(userId);
159                    }
160                }
161            };
162
163            IntentFilter intentFilter = new IntentFilter();
164            intentFilter.addAction(Intent.ACTION_USER_ADDED);
165            intentFilter.addAction(Intent.ACTION_USER_REMOVED);
166            mContext.registerReceiverAsUser(
167                    mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
168        }
169
170        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
171        // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
172        mNetworkCapabilities = new NetworkCapabilities();
173        mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
174        mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
175    }
176
177    /**
178     * Set if this object is responsible for showing its own notifications. When
179     * {@code false}, notifications are handled externally by someone else.
180     */
181    public void setEnableNotifications(boolean enableNotif) {
182        mEnableNotif = enableNotif;
183    }
184
185    /**
186     * Set if this object is responsible for watching for {@link NetworkInfo}
187     * teardown. When {@code false}, teardown is handled externally by someone
188     * else.
189     */
190    public void setEnableTeardown(boolean enableTeardown) {
191        mEnableTeardown = enableTeardown;
192    }
193
194    /**
195     * Update current state, dispaching event to listeners.
196     */
197    private void updateState(DetailedState detailedState, String reason) {
198        if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
199        mNetworkInfo.setDetailedState(detailedState, reason, null);
200        if (mNetworkAgent != null) {
201            mNetworkAgent.sendNetworkInfo(mNetworkInfo);
202        }
203    }
204
205    /**
206     * Prepare for a VPN application. This method is designed to solve
207     * race conditions. It first compares the current prepared package
208     * with {@code oldPackage}. If they are the same, the prepared
209     * package is revoked and replaced with {@code newPackage}. If
210     * {@code oldPackage} is {@code null}, the comparison is omitted.
211     * If {@code newPackage} is the same package or {@code null}, the
212     * revocation is omitted. This method returns {@code true} if the
213     * operation is succeeded.
214     *
215     * Legacy VPN is handled specially since it is not a real package.
216     * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
217     * it can be revoked by itself.
218     *
219     * @param oldPackage The package name of the old VPN application.
220     * @param newPackage The package name of the new VPN application.
221     * @return true if the operation is succeeded.
222     */
223    public synchronized boolean prepare(String oldPackage, String newPackage) {
224        // Return false if the package does not match.
225        if (oldPackage != null && !oldPackage.equals(mPackage)) {
226            return false;
227        }
228
229        // Return true if we do not need to revoke.
230        if (newPackage == null ||
231                (newPackage.equals(mPackage) && !newPackage.equals(VpnConfig.LEGACY_VPN))) {
232            return true;
233        }
234
235        // Check if the caller is authorized.
236        enforceControlPermission();
237
238        // Reset the interface and hide the notification.
239        if (mInterface != null) {
240            for (UidRange uidRange : mVpnUsers) {
241                hideNotification(uidRange.getStartUser());
242            }
243            agentDisconnect();
244            jniReset(mInterface);
245            mInterface = null;
246            mVpnUsers = null;
247        }
248
249        // Revoke the connection or stop LegacyVpnRunner.
250        if (mConnection != null) {
251            try {
252                mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
253                        Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
254            } catch (Exception e) {
255                // ignore
256            }
257            mContext.unbindService(mConnection);
258            mConnection = null;
259        } else if (mLegacyVpnRunner != null) {
260            mLegacyVpnRunner.exit();
261            mLegacyVpnRunner = null;
262        }
263
264        long token = Binder.clearCallingIdentity();
265        try {
266            mNetd.denyProtect(mOwnerUID);
267        } catch (Exception e) {
268            Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
269        } finally {
270            Binder.restoreCallingIdentity(token);
271        }
272
273        Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
274        mPackage = newPackage;
275        mOwnerUID = getAppUid(newPackage);
276        token = Binder.clearCallingIdentity();
277        try {
278            mNetd.allowProtect(mOwnerUID);
279        } catch (Exception e) {
280            Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
281        } finally {
282            Binder.restoreCallingIdentity(token);
283        }
284        mConfig = null;
285        updateState(DetailedState.IDLE, "prepare");
286        return true;
287    }
288
289    private int getAppUid(String app) {
290        if (app == VpnConfig.LEGACY_VPN) {
291            return Process.myUid();
292        }
293        PackageManager pm = mContext.getPackageManager();
294        int result;
295        try {
296            result = pm.getPackageUid(app, mUserId);
297        } catch (NameNotFoundException e) {
298            result = -1;
299        }
300        return result;
301    }
302
303    public NetworkInfo getNetworkInfo() {
304        return mNetworkInfo;
305    }
306
307    private void agentConnect() {
308        LinkProperties lp = new LinkProperties();
309        lp.setInterfaceName(mInterface);
310        boolean hasDefaultRoute = false;
311        for (RouteInfo route : mConfig.routes) {
312            lp.addRoute(route);
313            if (route.isDefaultRoute()) hasDefaultRoute = true;
314        }
315        if (hasDefaultRoute) {
316            mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
317        } else {
318            mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
319        }
320        if (mConfig.dnsServers != null) {
321            for (String dnsServer : mConfig.dnsServers) {
322                lp.addDnsServer(InetAddress.parseNumericAddress(dnsServer));
323            }
324        }
325        // Concatenate search domains into a string.
326        StringBuilder buffer = new StringBuilder();
327        if (mConfig.searchDomains != null) {
328            for (String domain : mConfig.searchDomains) {
329                buffer.append(domain).append(' ');
330            }
331        }
332        lp.setDomains(buffer.toString().trim());
333        mNetworkInfo.setIsAvailable(true);
334        mNetworkInfo.setDetailedState(DetailedState.CONNECTED, null, null);
335        NetworkMisc networkMisc = new NetworkMisc();
336        if (mConfig.allowBypass) {
337            networkMisc.allowBypass = true;
338        }
339        long token = Binder.clearCallingIdentity();
340        try {
341            mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
342                    mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
343                            public void unwanted() {
344                                // We are user controlled, not driven by NetworkRequest.
345                            };
346                        };
347        } finally {
348            Binder.restoreCallingIdentity(token);
349        }
350        addVpnUserLocked(mUserId);
351        // If we are owner assign all Restricted Users to this VPN
352        if (mUserId == UserHandle.USER_OWNER) {
353            token = Binder.clearCallingIdentity();
354            List<UserInfo> users;
355            try {
356                users = UserManager.get(mContext).getUsers();
357            } finally {
358                Binder.restoreCallingIdentity(token);
359            }
360            for (UserInfo user : users) {
361                if (user.isRestricted()) {
362                    addVpnUserLocked(user.id);
363                }
364            }
365        }
366        mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
367    }
368
369    private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
370        networkInfo.setIsAvailable(false);
371        networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
372        if (networkAgent != null) {
373            networkAgent.sendNetworkInfo(networkInfo);
374        }
375    }
376
377    private void agentDisconnect(NetworkAgent networkAgent) {
378        NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
379        agentDisconnect(networkInfo, networkAgent);
380    }
381
382    private void agentDisconnect() {
383        if (mNetworkInfo.isConnected()) {
384            agentDisconnect(mNetworkInfo, mNetworkAgent);
385            mNetworkAgent = null;
386        }
387    }
388
389    /**
390     * Establish a VPN network and return the file descriptor of the VPN
391     * interface. This methods returns {@code null} if the application is
392     * revoked or not prepared.
393     *
394     * @param config The parameters to configure the network.
395     * @return The file descriptor of the VPN interface.
396     */
397    public synchronized ParcelFileDescriptor establish(VpnConfig config) {
398        // Check if the caller is already prepared.
399        UserManager mgr = UserManager.get(mContext);
400        if (Binder.getCallingUid() != mOwnerUID) {
401            return null;
402        }
403        // Check if the service is properly declared.
404        Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
405        intent.setClassName(mPackage, config.user);
406        long token = Binder.clearCallingIdentity();
407        try {
408            // Restricted users are not allowed to create VPNs, they are tied to Owner
409            UserInfo user = mgr.getUserInfo(mUserId);
410            if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
411                throw new SecurityException("Restricted users cannot establish VPNs");
412            }
413
414            ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
415                                                                        null, 0, mUserId);
416            if (info == null) {
417                throw new SecurityException("Cannot find " + config.user);
418            }
419            if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
420                throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
421            }
422        } catch (RemoteException e) {
423                throw new SecurityException("Cannot find " + config.user);
424        } finally {
425            Binder.restoreCallingIdentity(token);
426        }
427
428        // Save the old config in case we need to go back.
429        VpnConfig oldConfig = mConfig;
430        String oldInterface = mInterface;
431        Connection oldConnection = mConnection;
432        NetworkAgent oldNetworkAgent = mNetworkAgent;
433        mNetworkAgent = null;
434        List<UidRange> oldUsers = mVpnUsers;
435
436        // Configure the interface. Abort if any of these steps fails.
437        ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
438        try {
439            updateState(DetailedState.CONNECTING, "establish");
440            String interfaze = jniGetName(tun.getFd());
441
442            // TEMP use the old jni calls until there is support for netd address setting
443            StringBuilder builder = new StringBuilder();
444            for (LinkAddress address : config.addresses) {
445                builder.append(" " + address);
446            }
447            if (jniSetAddresses(interfaze, builder.toString()) < 1) {
448                throw new IllegalArgumentException("At least one address must be specified");
449            }
450            Connection connection = new Connection();
451            if (!mContext.bindServiceAsUser(intent, connection, Context.BIND_AUTO_CREATE,
452                        new UserHandle(mUserId))) {
453                throw new IllegalStateException("Cannot bind " + config.user);
454            }
455
456            mConnection = connection;
457            mInterface = interfaze;
458
459            // Fill more values.
460            config.user = mPackage;
461            config.interfaze = mInterface;
462            config.startTime = SystemClock.elapsedRealtime();
463            mConfig = config;
464
465            // Set up forwarding and DNS rules.
466            mVpnUsers = new ArrayList<UidRange>();
467            agentConnect();
468
469            if (oldConnection != null) {
470                mContext.unbindService(oldConnection);
471            }
472            // Remove the old tun's user forwarding rules
473            // The new tun's user rules have already been added so they will take over
474            // as rules are deleted. This prevents data leakage as the rules are moved over.
475            agentDisconnect(oldNetworkAgent);
476            if (oldInterface != null && !oldInterface.equals(interfaze)) {
477                jniReset(oldInterface);
478            }
479
480            try {
481                IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
482            } catch (IOException e) {
483                throw new IllegalStateException(
484                        "Cannot set tunnel's fd as blocking=" + config.blocking, e);
485            }
486        } catch (RuntimeException e) {
487            IoUtils.closeQuietly(tun);
488            agentDisconnect();
489            // restore old state
490            mConfig = oldConfig;
491            mConnection = oldConnection;
492            mVpnUsers = oldUsers;
493            mNetworkAgent = oldNetworkAgent;
494            mInterface = oldInterface;
495            throw e;
496        }
497        Log.i(TAG, "Established by " + config.user + " on " + mInterface);
498        return tun;
499    }
500
501    private boolean isRunningLocked() {
502        return mVpnUsers != null;
503    }
504
505    // Note: This function adds to mVpnUsers but does not publish list to NetworkAgent.
506    private void addVpnUserLocked(int user) {
507        if (!isRunningLocked()) {
508            throw new IllegalStateException("VPN is not active");
509        }
510
511        // add the user
512        mVpnUsers.add(UidRange.createForUser(user));
513
514        // show the notification
515        if (!mPackage.equals(VpnConfig.LEGACY_VPN)) {
516            // Load everything for the user's notification
517            PackageManager pm = mContext.getPackageManager();
518            ApplicationInfo app = null;
519            final long token = Binder.clearCallingIdentity();
520            try {
521                app = AppGlobals.getPackageManager().getApplicationInfo(mPackage, 0, mUserId);
522            } catch (RemoteException e) {
523                throw new IllegalStateException("Invalid application");
524            } finally {
525                Binder.restoreCallingIdentity(token);
526            }
527            String label = app.loadLabel(pm).toString();
528            // Load the icon and convert it into a bitmap.
529            Drawable icon = app.loadIcon(pm);
530            Bitmap bitmap = null;
531            if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
532                int width = mContext.getResources().getDimensionPixelSize(
533                        android.R.dimen.notification_large_icon_width);
534                int height = mContext.getResources().getDimensionPixelSize(
535                        android.R.dimen.notification_large_icon_height);
536                icon.setBounds(0, 0, width, height);
537                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
538                Canvas c = new Canvas(bitmap);
539                icon.draw(c);
540                c.setBitmap(null);
541            }
542            showNotification(label, bitmap, user);
543        } else {
544            showNotification(null, null, user);
545        }
546    }
547
548    private void removeVpnUserLocked(int user) {
549            if (!isRunningLocked()) {
550                throw new IllegalStateException("VPN is not active");
551            }
552            UidRange uidRange = UidRange.createForUser(user);
553            if (mNetworkAgent != null) {
554                mNetworkAgent.removeUidRanges(new UidRange[] { uidRange });
555            }
556            mVpnUsers.remove(uidRange);
557            hideNotification(user);
558    }
559
560    private void onUserAdded(int userId) {
561        // If the user is restricted tie them to the owner's VPN
562        synchronized(Vpn.this) {
563            UserManager mgr = UserManager.get(mContext);
564            UserInfo user = mgr.getUserInfo(userId);
565            if (user.isRestricted()) {
566                try {
567                    addVpnUserLocked(userId);
568                    if (mNetworkAgent != null) {
569                        UidRange uidRange = UidRange.createForUser(userId);
570                        mNetworkAgent.addUidRanges(new UidRange[] { uidRange });
571                    }
572                } catch (Exception e) {
573                    Log.wtf(TAG, "Failed to add restricted user to owner", e);
574                }
575            }
576        }
577    }
578
579    private void onUserRemoved(int userId) {
580        // clean up if restricted
581        synchronized(Vpn.this) {
582            UserManager mgr = UserManager.get(mContext);
583            UserInfo user = mgr.getUserInfo(userId);
584            if (user.isRestricted()) {
585                try {
586                    removeVpnUserLocked(userId);
587                } catch (Exception e) {
588                    Log.wtf(TAG, "Failed to remove restricted user to owner", e);
589                }
590            }
591        }
592    }
593
594    /**
595     * Return the configuration of the currently running VPN.
596     */
597    public VpnConfig getVpnConfig() {
598        enforceControlPermission();
599        return mConfig;
600    }
601
602    @Deprecated
603    public synchronized void interfaceStatusChanged(String iface, boolean up) {
604        try {
605            mObserver.interfaceStatusChanged(iface, up);
606        } catch (RemoteException e) {
607            // ignored; target is local
608        }
609    }
610
611    private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
612        @Override
613        public void interfaceStatusChanged(String interfaze, boolean up) {
614            synchronized (Vpn.this) {
615                if (!up && mLegacyVpnRunner != null) {
616                    mLegacyVpnRunner.check(interfaze);
617                }
618            }
619        }
620
621        @Override
622        public void interfaceRemoved(String interfaze) {
623            synchronized (Vpn.this) {
624                if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
625                    for (UidRange uidRange : mVpnUsers) {
626                        hideNotification(uidRange.getStartUser());
627                    }
628                    mVpnUsers = null;
629                    mInterface = null;
630                    if (mConnection != null) {
631                        mContext.unbindService(mConnection);
632                        mConnection = null;
633                        agentDisconnect();
634                    } else if (mLegacyVpnRunner != null) {
635                        mLegacyVpnRunner.exit();
636                        mLegacyVpnRunner = null;
637                    }
638                }
639            }
640        }
641    };
642
643    private void enforceControlPermission() {
644        // System user is allowed to control VPN.
645        if (Binder.getCallingUid() == Process.SYSTEM_UID) {
646            return;
647        }
648        int appId = UserHandle.getAppId(Binder.getCallingUid());
649        final long token = Binder.clearCallingIdentity();
650        try {
651            // System VPN dialogs are also allowed to control VPN.
652            PackageManager pm = mContext.getPackageManager();
653            ApplicationInfo app = pm.getApplicationInfo(VpnConfig.DIALOGS_PACKAGE, 0);
654            if (((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) && (appId == app.uid)) {
655                return;
656            }
657        } catch (Exception e) {
658            // ignore
659        } finally {
660            Binder.restoreCallingIdentity(token);
661        }
662
663        throw new SecurityException("Unauthorized Caller");
664    }
665
666    private class Connection implements ServiceConnection {
667        private IBinder mService;
668
669        @Override
670        public void onServiceConnected(ComponentName name, IBinder service) {
671            mService = service;
672        }
673
674        @Override
675        public void onServiceDisconnected(ComponentName name) {
676            mService = null;
677        }
678    }
679
680    private void showNotification(String label, Bitmap icon, int user) {
681        if (!mEnableNotif) return;
682        final long token = Binder.clearCallingIdentity();
683        try {
684            mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
685
686            NotificationManager nm = (NotificationManager)
687                    mContext.getSystemService(Context.NOTIFICATION_SERVICE);
688
689            if (nm != null) {
690                String title = (label == null) ? mContext.getString(R.string.vpn_title) :
691                        mContext.getString(R.string.vpn_title_long, label);
692                String text = (mConfig.session == null) ? mContext.getString(R.string.vpn_text) :
693                        mContext.getString(R.string.vpn_text_long, mConfig.session);
694
695                Notification notification = new Notification.Builder(mContext)
696                        .setSmallIcon(R.drawable.vpn_connected)
697                        .setLargeIcon(icon)
698                        .setContentTitle(title)
699                        .setContentText(text)
700                        .setContentIntent(mStatusIntent)
701                        .setDefaults(0)
702                        .setOngoing(true)
703                        .build();
704                nm.notifyAsUser(null, R.drawable.vpn_connected, notification, new UserHandle(user));
705            }
706        } finally {
707            Binder.restoreCallingIdentity(token);
708        }
709    }
710
711    private void hideNotification(int user) {
712        if (!mEnableNotif) return;
713        mStatusIntent = null;
714
715        NotificationManager nm = (NotificationManager)
716                mContext.getSystemService(Context.NOTIFICATION_SERVICE);
717
718        if (nm != null) {
719            final long token = Binder.clearCallingIdentity();
720            try {
721                nm.cancelAsUser(null, R.drawable.vpn_connected, new UserHandle(user));
722            } finally {
723                Binder.restoreCallingIdentity(token);
724            }
725        }
726    }
727
728    private native int jniCreate(int mtu);
729    private native String jniGetName(int tun);
730    private native int jniSetAddresses(String interfaze, String addresses);
731    private native void jniReset(String interfaze);
732    private native int jniCheck(String interfaze);
733
734    private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
735        for (RouteInfo route : prop.getAllRoutes()) {
736            // Currently legacy VPN only works on IPv4.
737            if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
738                return route;
739            }
740        }
741
742        throw new IllegalStateException("Unable to find IPv4 default gateway");
743    }
744
745    /**
746     * Start legacy VPN, controlling native daemons as needed. Creates a
747     * secondary thread to perform connection work, returning quickly.
748     */
749    public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
750        enforceControlPermission();
751        if (!keyStore.isUnlocked()) {
752            throw new IllegalStateException("KeyStore isn't unlocked");
753        }
754        UserManager mgr = UserManager.get(mContext);
755        UserInfo user = mgr.getUserInfo(mUserId);
756        if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
757            throw new SecurityException("Restricted users cannot establish VPNs");
758        }
759
760        final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
761        final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
762        final String iface = ipv4DefaultRoute.getInterface();
763
764        // Load certificates.
765        String privateKey = "";
766        String userCert = "";
767        String caCert = "";
768        String serverCert = "";
769        if (!profile.ipsecUserCert.isEmpty()) {
770            privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
771            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
772            userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
773        }
774        if (!profile.ipsecCaCert.isEmpty()) {
775            byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
776            caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
777        }
778        if (!profile.ipsecServerCert.isEmpty()) {
779            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
780            serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
781        }
782        if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
783            throw new IllegalStateException("Cannot load credentials");
784        }
785
786        // Prepare arguments for racoon.
787        String[] racoon = null;
788        switch (profile.type) {
789            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
790                racoon = new String[] {
791                    iface, profile.server, "udppsk", profile.ipsecIdentifier,
792                    profile.ipsecSecret, "1701",
793                };
794                break;
795            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
796                racoon = new String[] {
797                    iface, profile.server, "udprsa", privateKey, userCert,
798                    caCert, serverCert, "1701",
799                };
800                break;
801            case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
802                racoon = new String[] {
803                    iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
804                    profile.ipsecSecret, profile.username, profile.password, "", gateway,
805                };
806                break;
807            case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
808                racoon = new String[] {
809                    iface, profile.server, "xauthrsa", privateKey, userCert,
810                    caCert, serverCert, profile.username, profile.password, "", gateway,
811                };
812                break;
813            case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
814                racoon = new String[] {
815                    iface, profile.server, "hybridrsa",
816                    caCert, serverCert, profile.username, profile.password, "", gateway,
817                };
818                break;
819        }
820
821        // Prepare arguments for mtpd.
822        String[] mtpd = null;
823        switch (profile.type) {
824            case VpnProfile.TYPE_PPTP:
825                mtpd = new String[] {
826                    iface, "pptp", profile.server, "1723",
827                    "name", profile.username, "password", profile.password,
828                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
829                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
830                    (profile.mppe ? "+mppe" : "nomppe"),
831                };
832                break;
833            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
834            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
835                mtpd = new String[] {
836                    iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
837                    "name", profile.username, "password", profile.password,
838                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
839                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
840                };
841                break;
842        }
843
844        VpnConfig config = new VpnConfig();
845        config.legacy = true;
846        config.user = profile.key;
847        config.interfaze = iface;
848        config.session = profile.name;
849
850        config.addLegacyRoutes(profile.routes);
851        if (!profile.dnsServers.isEmpty()) {
852            config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
853        }
854        if (!profile.searchDomains.isEmpty()) {
855            config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
856        }
857        startLegacyVpn(config, racoon, mtpd);
858    }
859
860    private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
861        stopLegacyVpn();
862
863        // Prepare for the new request. This also checks the caller.
864        prepare(null, VpnConfig.LEGACY_VPN);
865        updateState(DetailedState.CONNECTING, "startLegacyVpn");
866
867        // Start a new LegacyVpnRunner and we are done!
868        mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
869        mLegacyVpnRunner.start();
870    }
871
872    public synchronized void stopLegacyVpn() {
873        if (mLegacyVpnRunner != null) {
874            mLegacyVpnRunner.exit();
875            mLegacyVpnRunner = null;
876
877            synchronized (LegacyVpnRunner.TAG) {
878                // wait for old thread to completely finish before spinning up
879                // new instance, otherwise state updates can be out of order.
880            }
881        }
882    }
883
884    /**
885     * Return the information of the current ongoing legacy VPN.
886     */
887    public synchronized LegacyVpnInfo getLegacyVpnInfo() {
888        // Check if the caller is authorized.
889        enforceControlPermission();
890        if (mLegacyVpnRunner == null) return null;
891
892        final LegacyVpnInfo info = new LegacyVpnInfo();
893        info.key = mConfig.user;
894        info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
895        if (mNetworkInfo.isConnected()) {
896            info.intent = mStatusIntent;
897        }
898        return info;
899    }
900
901    public VpnConfig getLegacyVpnConfig() {
902        if (mLegacyVpnRunner != null) {
903            return mConfig;
904        } else {
905            return null;
906        }
907    }
908
909    /**
910     * Bringing up a VPN connection takes time, and that is all this thread
911     * does. Here we have plenty of time. The only thing we need to take
912     * care of is responding to interruptions as soon as possible. Otherwise
913     * requests will be piled up. This can be done in a Handler as a state
914     * machine, but it is much easier to read in the current form.
915     */
916    private class LegacyVpnRunner extends Thread {
917        private static final String TAG = "LegacyVpnRunner";
918
919        private final String[] mDaemons;
920        private final String[][] mArguments;
921        private final LocalSocket[] mSockets;
922        private final String mOuterInterface;
923        private final AtomicInteger mOuterConnection =
924                new AtomicInteger(ConnectivityManager.TYPE_NONE);
925
926        private long mTimer = -1;
927
928        /**
929         * Watch for the outer connection (passing in the constructor) going away.
930         */
931        private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
932            @Override
933            public void onReceive(Context context, Intent intent) {
934                if (!mEnableTeardown) return;
935
936                if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
937                    if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
938                            ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
939                        NetworkInfo info = (NetworkInfo)intent.getExtra(
940                                ConnectivityManager.EXTRA_NETWORK_INFO);
941                        if (info != null && !info.isConnectedOrConnecting()) {
942                            try {
943                                mObserver.interfaceStatusChanged(mOuterInterface, false);
944                            } catch (RemoteException e) {}
945                        }
946                    }
947                }
948            }
949        };
950
951        public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
952            super(TAG);
953            mConfig = config;
954            mDaemons = new String[] {"racoon", "mtpd"};
955            // TODO: clear arguments from memory once launched
956            mArguments = new String[][] {racoon, mtpd};
957            mSockets = new LocalSocket[mDaemons.length];
958
959            // This is the interface which VPN is running on,
960            // mConfig.interfaze will change to point to OUR
961            // internal interface soon. TODO - add inner/outer to mconfig
962            // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
963            // we will leave the VPN up.  We should check that it's still there/connected after
964            // registering
965            mOuterInterface = mConfig.interfaze;
966
967            try {
968                mOuterConnection.set(
969                        mConnService.findConnectionTypeForIface(mOuterInterface));
970            } catch (Exception e) {
971                mOuterConnection.set(ConnectivityManager.TYPE_NONE);
972            }
973
974            IntentFilter filter = new IntentFilter();
975            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
976            mContext.registerReceiver(mBroadcastReceiver, filter);
977        }
978
979        public void check(String interfaze) {
980            if (interfaze.equals(mOuterInterface)) {
981                Log.i(TAG, "Legacy VPN is going down with " + interfaze);
982                exit();
983            }
984        }
985
986        public void exit() {
987            // We assume that everything is reset after stopping the daemons.
988            interrupt();
989            for (LocalSocket socket : mSockets) {
990                IoUtils.closeQuietly(socket);
991            }
992            agentDisconnect();
993            try {
994                mContext.unregisterReceiver(mBroadcastReceiver);
995            } catch (IllegalArgumentException e) {}
996        }
997
998        @Override
999        public void run() {
1000            // Wait for the previous thread since it has been interrupted.
1001            Log.v(TAG, "Waiting");
1002            synchronized (TAG) {
1003                Log.v(TAG, "Executing");
1004                execute();
1005                monitorDaemons();
1006            }
1007        }
1008
1009        private void checkpoint(boolean yield) throws InterruptedException {
1010            long now = SystemClock.elapsedRealtime();
1011            if (mTimer == -1) {
1012                mTimer = now;
1013                Thread.sleep(1);
1014            } else if (now - mTimer <= 60000) {
1015                Thread.sleep(yield ? 200 : 1);
1016            } else {
1017                updateState(DetailedState.FAILED, "checkpoint");
1018                throw new IllegalStateException("Time is up");
1019            }
1020        }
1021
1022        private void execute() {
1023            // Catch all exceptions so we can clean up few things.
1024            boolean initFinished = false;
1025            try {
1026                // Initialize the timer.
1027                checkpoint(false);
1028
1029                // Wait for the daemons to stop.
1030                for (String daemon : mDaemons) {
1031                    while (!SystemService.isStopped(daemon)) {
1032                        checkpoint(true);
1033                    }
1034                }
1035
1036                // Clear the previous state.
1037                File state = new File("/data/misc/vpn/state");
1038                state.delete();
1039                if (state.exists()) {
1040                    throw new IllegalStateException("Cannot delete the state");
1041                }
1042                new File("/data/misc/vpn/abort").delete();
1043                initFinished = true;
1044
1045                // Check if we need to restart any of the daemons.
1046                boolean restart = false;
1047                for (String[] arguments : mArguments) {
1048                    restart = restart || (arguments != null);
1049                }
1050                if (!restart) {
1051                    agentDisconnect();
1052                    return;
1053                }
1054                updateState(DetailedState.CONNECTING, "execute");
1055
1056                // Start the daemon with arguments.
1057                for (int i = 0; i < mDaemons.length; ++i) {
1058                    String[] arguments = mArguments[i];
1059                    if (arguments == null) {
1060                        continue;
1061                    }
1062
1063                    // Start the daemon.
1064                    String daemon = mDaemons[i];
1065                    SystemService.start(daemon);
1066
1067                    // Wait for the daemon to start.
1068                    while (!SystemService.isRunning(daemon)) {
1069                        checkpoint(true);
1070                    }
1071
1072                    // Create the control socket.
1073                    mSockets[i] = new LocalSocket();
1074                    LocalSocketAddress address = new LocalSocketAddress(
1075                            daemon, LocalSocketAddress.Namespace.RESERVED);
1076
1077                    // Wait for the socket to connect.
1078                    while (true) {
1079                        try {
1080                            mSockets[i].connect(address);
1081                            break;
1082                        } catch (Exception e) {
1083                            // ignore
1084                        }
1085                        checkpoint(true);
1086                    }
1087                    mSockets[i].setSoTimeout(500);
1088
1089                    // Send over the arguments.
1090                    OutputStream out = mSockets[i].getOutputStream();
1091                    for (String argument : arguments) {
1092                        byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
1093                        if (bytes.length >= 0xFFFF) {
1094                            throw new IllegalArgumentException("Argument is too large");
1095                        }
1096                        out.write(bytes.length >> 8);
1097                        out.write(bytes.length);
1098                        out.write(bytes);
1099                        checkpoint(false);
1100                    }
1101                    out.write(0xFF);
1102                    out.write(0xFF);
1103                    out.flush();
1104
1105                    // Wait for End-of-File.
1106                    InputStream in = mSockets[i].getInputStream();
1107                    while (true) {
1108                        try {
1109                            if (in.read() == -1) {
1110                                break;
1111                            }
1112                        } catch (Exception e) {
1113                            // ignore
1114                        }
1115                        checkpoint(true);
1116                    }
1117                }
1118
1119                // Wait for the daemons to create the new state.
1120                while (!state.exists()) {
1121                    // Check if a running daemon is dead.
1122                    for (int i = 0; i < mDaemons.length; ++i) {
1123                        String daemon = mDaemons[i];
1124                        if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
1125                            throw new IllegalStateException(daemon + " is dead");
1126                        }
1127                    }
1128                    checkpoint(true);
1129                }
1130
1131                // Now we are connected. Read and parse the new state.
1132                String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
1133                if (parameters.length != 6) {
1134                    throw new IllegalStateException("Cannot parse the state");
1135                }
1136
1137                // Set the interface and the addresses in the config.
1138                mConfig.interfaze = parameters[0].trim();
1139
1140                mConfig.addLegacyAddresses(parameters[1]);
1141                // Set the routes if they are not set in the config.
1142                if (mConfig.routes == null || mConfig.routes.isEmpty()) {
1143                    mConfig.addLegacyRoutes(parameters[2]);
1144                }
1145
1146                // Set the DNS servers if they are not set in the config.
1147                if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
1148                    String dnsServers = parameters[3].trim();
1149                    if (!dnsServers.isEmpty()) {
1150                        mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1151                    }
1152                }
1153
1154                // Set the search domains if they are not set in the config.
1155                if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1156                    String searchDomains = parameters[4].trim();
1157                    if (!searchDomains.isEmpty()) {
1158                        mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1159                    }
1160                }
1161
1162                // Here is the last step and it must be done synchronously.
1163                synchronized (Vpn.this) {
1164                    // Set the start time
1165                    mConfig.startTime = SystemClock.elapsedRealtime();
1166
1167                    // Check if the thread is interrupted while we are waiting.
1168                    checkpoint(false);
1169
1170                    // Check if the interface is gone while we are waiting.
1171                    if (jniCheck(mConfig.interfaze) == 0) {
1172                        throw new IllegalStateException(mConfig.interfaze + " is gone");
1173                    }
1174
1175                    // Now INetworkManagementEventObserver is watching our back.
1176                    mInterface = mConfig.interfaze;
1177                    mVpnUsers = new ArrayList<UidRange>();
1178
1179                    agentConnect();
1180
1181                    Log.i(TAG, "Connected!");
1182                }
1183            } catch (Exception e) {
1184                Log.i(TAG, "Aborting", e);
1185                exit();
1186            } finally {
1187                // Kill the daemons if they fail to stop.
1188                if (!initFinished) {
1189                    for (String daemon : mDaemons) {
1190                        SystemService.stop(daemon);
1191                    }
1192                }
1193
1194                // Do not leave an unstable state.
1195                if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1196                    agentDisconnect();
1197                }
1198            }
1199        }
1200
1201        /**
1202         * Monitor the daemons we started, moving to disconnected state if the
1203         * underlying services fail.
1204         */
1205        private void monitorDaemons() {
1206            if (!mNetworkInfo.isConnected()) {
1207                return;
1208            }
1209
1210            try {
1211                while (true) {
1212                    Thread.sleep(2000);
1213                    for (int i = 0; i < mDaemons.length; i++) {
1214                        if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1215                            return;
1216                        }
1217                    }
1218                }
1219            } catch (InterruptedException e) {
1220                Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1221            } finally {
1222                for (String daemon : mDaemons) {
1223                    SystemService.stop(daemon);
1224                }
1225
1226                agentDisconnect();
1227            }
1228        }
1229    }
1230}
1231