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