Vpn.java revision ebbcb54a4380239ea3d0c4d1a20cd6b3c9ec0590
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.net.ConnectivityManager.NETID_UNSET;
21import static android.net.RouteInfo.RTN_THROW;
22import static android.net.RouteInfo.RTN_UNREACHABLE;
23
24import android.Manifest;
25import android.annotation.NonNull;
26import android.annotation.Nullable;
27import android.annotation.UserIdInt;
28import android.app.AppGlobals;
29import android.app.AppOpsManager;
30import android.app.PendingIntent;
31import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.pm.PackageManager;
38import android.content.pm.PackageManager.NameNotFoundException;
39import android.content.pm.ResolveInfo;
40import android.content.pm.UserInfo;
41import android.net.ConnectivityManager;
42import android.net.INetworkManagementEventObserver;
43import android.net.IpPrefix;
44import android.net.LinkAddress;
45import android.net.LinkProperties;
46import android.net.LocalSocket;
47import android.net.LocalSocketAddress;
48import android.net.Network;
49import android.net.NetworkAgent;
50import android.net.NetworkCapabilities;
51import android.net.NetworkInfo;
52import android.net.NetworkInfo.DetailedState;
53import android.net.NetworkMisc;
54import android.net.RouteInfo;
55import android.net.UidRange;
56import android.os.Binder;
57import android.os.FileUtils;
58import android.os.IBinder;
59import android.os.INetworkManagementService;
60import android.os.Looper;
61import android.os.Parcel;
62import android.os.ParcelFileDescriptor;
63import android.os.Process;
64import android.os.RemoteException;
65import android.os.SystemClock;
66import android.os.SystemService;
67import android.os.UserHandle;
68import android.os.UserManager;
69import android.security.Credentials;
70import android.security.KeyStore;
71import android.text.TextUtils;
72import android.util.ArraySet;
73import android.util.Log;
74
75import com.android.internal.annotations.GuardedBy;
76import com.android.internal.annotations.VisibleForTesting;
77import com.android.internal.net.LegacyVpnInfo;
78import com.android.internal.net.VpnConfig;
79import com.android.internal.net.VpnInfo;
80import com.android.internal.net.VpnProfile;
81import com.android.server.net.BaseNetworkObserver;
82
83import libcore.io.IoUtils;
84
85import java.io.File;
86import java.io.IOException;
87import java.io.InputStream;
88import java.io.OutputStream;
89import java.net.Inet4Address;
90import java.net.Inet6Address;
91import java.net.InetAddress;
92import java.nio.charset.StandardCharsets;
93import java.util.ArrayList;
94import java.util.Arrays;
95import java.util.Collection;
96import java.util.Collections;
97import java.util.List;
98import java.util.Set;
99import java.util.SortedSet;
100import java.util.TreeSet;
101import java.util.concurrent.atomic.AtomicInteger;
102
103/**
104 * @hide
105 */
106public class Vpn {
107    private static final String NETWORKTYPE = "VPN";
108    private static final String TAG = "Vpn";
109    private static final boolean LOGD = true;
110
111    // TODO: create separate trackers for each unique VPN to support
112    // automated reconnection
113
114    private Context mContext;
115    private NetworkInfo mNetworkInfo;
116    private String mPackage;
117    private int mOwnerUID;
118    private String mInterface;
119    private Connection mConnection;
120    private LegacyVpnRunner mLegacyVpnRunner;
121    private PendingIntent mStatusIntent;
122    private volatile boolean mEnableTeardown = true;
123    private final INetworkManagementService mNetd;
124    private VpnConfig mConfig;
125    private NetworkAgent mNetworkAgent;
126    private final Looper mLooper;
127    private final NetworkCapabilities mNetworkCapabilities;
128
129    /**
130     * Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
131     * only applies to {@link VpnService} connections.
132     */
133    private boolean mAlwaysOn = false;
134
135    /**
136     * Whether to disable traffic outside of this VPN even when the VPN is not connected. System
137     * apps can still bypass by choosing explicit networks. Has no effect if {@link mAlwaysOn} is
138     * not set.
139     */
140    private boolean mLockdown = false;
141
142    /**
143     * List of UIDs that are set to use this VPN by default. Normally, every UID in the user is
144     * added to this set but that can be changed by adding allowed or disallowed applications. It
145     * is non-null iff the VPN is connected.
146     *
147     * Unless the VPN has set allowBypass=true, these UIDs are forced into the VPN.
148     *
149     * @see VpnService.Builder#addAllowedApplication(String)
150     * @see VpnService.Builder#addDisallowedApplication(String)
151     */
152    @GuardedBy("this")
153    private Set<UidRange> mVpnUsers = null;
154
155    /**
156     * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
157     * when VPN is not running. For example, during system startup or after a crash.
158     * @see mLockdown
159     */
160    @GuardedBy("this")
161    private Set<UidRange> mBlockedUsers = new ArraySet<>();
162
163    // Handle of user initiating VPN.
164    private final int mUserHandle;
165
166    public Vpn(Looper looper, Context context, INetworkManagementService netService,
167            int userHandle) {
168        mContext = context;
169        mNetd = netService;
170        mUserHandle = userHandle;
171        mLooper = looper;
172
173        mPackage = VpnConfig.LEGACY_VPN;
174        mOwnerUID = getAppUid(mPackage, mUserHandle);
175
176        try {
177            netService.registerObserver(mObserver);
178        } catch (RemoteException e) {
179            Log.wtf(TAG, "Problem registering observer", e);
180        }
181
182        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_VPN, 0, NETWORKTYPE, "");
183        // TODO: Copy metered attribute and bandwidths from physical transport, b/16207332
184        mNetworkCapabilities = new NetworkCapabilities();
185        mNetworkCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
186        mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
187    }
188
189    /**
190     * Set if this object is responsible for watching for {@link NetworkInfo}
191     * teardown. When {@code false}, teardown is handled externally by someone
192     * else.
193     */
194    public void setEnableTeardown(boolean enableTeardown) {
195        mEnableTeardown = enableTeardown;
196    }
197
198    /**
199     * Update current state, dispaching event to listeners.
200     */
201    private void updateState(DetailedState detailedState, String reason) {
202        if (LOGD) Log.d(TAG, "setting state=" + detailedState + ", reason=" + reason);
203        mNetworkInfo.setDetailedState(detailedState, reason, null);
204        if (mNetworkAgent != null) {
205            mNetworkAgent.sendNetworkInfo(mNetworkInfo);
206        }
207    }
208
209    /**
210     * Configures an always-on VPN connection through a specific application.
211     * This connection is automatically granted and persisted after a reboot.
212     *
213     * <p>The designated package should exist and declare a {@link VpnService} in its
214     *    manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
215     *    otherwise the call will fail.
216     *
217     * @param packageName the package to designate as always-on VPN supplier.
218     * @param lockdown whether to prevent traffic outside of a VPN, for example while connecting.
219     */
220    public synchronized boolean setAlwaysOnPackage(String packageName, boolean lockdown) {
221        enforceControlPermissionOrInternalCaller();
222
223        // Disconnect current VPN.
224        prepareInternal(VpnConfig.LEGACY_VPN);
225
226        // Pre-authorize new always-on VPN package.
227        if (packageName != null) {
228            if (!setPackageAuthorization(packageName, true)) {
229                return false;
230            }
231            prepareInternal(packageName);
232        }
233
234        mAlwaysOn = (packageName != null);
235        mLockdown = (mAlwaysOn && lockdown);
236        setVpnForcedLocked(mLockdown);
237        return true;
238    }
239
240    /**
241     * @return the package name of the VPN controller responsible for always-on VPN,
242     *         or {@code null} if none is set or always-on VPN is controlled through
243     *         lockdown instead.
244     * @hide
245     */
246    public synchronized String getAlwaysOnPackage() {
247        enforceControlPermissionOrInternalCaller();
248        return (mAlwaysOn ? mPackage : null);
249    }
250
251    /**
252     * Prepare for a VPN application. This method is designed to solve
253     * race conditions. It first compares the current prepared package
254     * with {@code oldPackage}. If they are the same, the prepared
255     * package is revoked and replaced with {@code newPackage}. If
256     * {@code oldPackage} is {@code null}, the comparison is omitted.
257     * If {@code newPackage} is the same package or {@code null}, the
258     * revocation is omitted. This method returns {@code true} if the
259     * operation is succeeded.
260     *
261     * Legacy VPN is handled specially since it is not a real package.
262     * It uses {@link VpnConfig#LEGACY_VPN} as its package name, and
263     * it can be revoked by itself.
264     *
265     * @param oldPackage The package name of the old VPN application.
266     * @param newPackage The package name of the new VPN application.
267     * @return true if the operation is succeeded.
268     */
269    public synchronized boolean prepare(String oldPackage, String newPackage) {
270        // Stop an existing always-on VPN from being dethroned by other apps.
271        if (mAlwaysOn && !TextUtils.equals(mPackage, newPackage)) {
272            return false;
273        }
274
275        if (oldPackage != null) {
276            if (getAppUid(oldPackage, mUserHandle) != mOwnerUID) {
277                // The package doesn't match. We return false (to obtain user consent) unless the
278                // user has already consented to that VPN package.
279                if (!oldPackage.equals(VpnConfig.LEGACY_VPN) && isVpnUserPreConsented(oldPackage)) {
280                    prepareInternal(oldPackage);
281                    return true;
282                }
283                return false;
284            } else if (!oldPackage.equals(VpnConfig.LEGACY_VPN)
285                    && !isVpnUserPreConsented(oldPackage)) {
286                // Currently prepared VPN is revoked, so unprepare it and return false.
287                prepareInternal(VpnConfig.LEGACY_VPN);
288                return false;
289            }
290        }
291
292        // Return true if we do not need to revoke.
293        if (newPackage == null || (!newPackage.equals(VpnConfig.LEGACY_VPN) &&
294                getAppUid(newPackage, mUserHandle) == mOwnerUID)) {
295            return true;
296        }
297
298        // Check that the caller is authorized.
299        enforceControlPermission();
300
301        prepareInternal(newPackage);
302        return true;
303    }
304
305    /** Prepare the VPN for the given package. Does not perform permission checks. */
306    private void prepareInternal(String newPackage) {
307        long token = Binder.clearCallingIdentity();
308        try {
309            // Reset the interface.
310            if (mInterface != null) {
311                mStatusIntent = null;
312                agentDisconnect();
313                jniReset(mInterface);
314                mInterface = null;
315                mVpnUsers = null;
316            }
317
318            // Revoke the connection or stop LegacyVpnRunner.
319            if (mConnection != null) {
320                try {
321                    mConnection.mService.transact(IBinder.LAST_CALL_TRANSACTION,
322                            Parcel.obtain(), null, IBinder.FLAG_ONEWAY);
323                } catch (Exception e) {
324                    // ignore
325                }
326                mContext.unbindService(mConnection);
327                mConnection = null;
328            } else if (mLegacyVpnRunner != null) {
329                mLegacyVpnRunner.exit();
330                mLegacyVpnRunner = null;
331            }
332
333            try {
334                mNetd.denyProtect(mOwnerUID);
335            } catch (Exception e) {
336                Log.wtf(TAG, "Failed to disallow UID " + mOwnerUID + " to call protect() " + e);
337            }
338
339            Log.i(TAG, "Switched from " + mPackage + " to " + newPackage);
340            mPackage = newPackage;
341            mOwnerUID = getAppUid(newPackage, mUserHandle);
342            try {
343                mNetd.allowProtect(mOwnerUID);
344            } catch (Exception e) {
345                Log.wtf(TAG, "Failed to allow UID " + mOwnerUID + " to call protect() " + e);
346            }
347            mConfig = null;
348
349            updateState(DetailedState.IDLE, "prepare");
350        } finally {
351            Binder.restoreCallingIdentity(token);
352        }
353    }
354
355    /**
356     * Set whether a package has the ability to launch VPNs without user intervention.
357     */
358    public boolean setPackageAuthorization(String packageName, boolean authorized) {
359        // Check if the caller is authorized.
360        enforceControlPermissionOrInternalCaller();
361
362        int uid = getAppUid(packageName, mUserHandle);
363        if (uid == -1 || VpnConfig.LEGACY_VPN.equals(packageName)) {
364            // Authorization for nonexistent packages (or fake ones) can't be updated.
365            return false;
366        }
367
368        long token = Binder.clearCallingIdentity();
369        try {
370            AppOpsManager appOps =
371                    (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
372            appOps.setMode(AppOpsManager.OP_ACTIVATE_VPN, uid, packageName,
373                    authorized ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
374            return true;
375        } catch (Exception e) {
376            Log.wtf(TAG, "Failed to set app ops for package " + packageName + ", uid " + uid, e);
377        } finally {
378            Binder.restoreCallingIdentity(token);
379        }
380        return false;
381    }
382
383    private boolean isVpnUserPreConsented(String packageName) {
384        AppOpsManager appOps =
385                (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
386
387        // Verify that the caller matches the given package and has permission to activate VPNs.
388        return appOps.noteOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, Binder.getCallingUid(),
389                packageName) == AppOpsManager.MODE_ALLOWED;
390    }
391
392    private int getAppUid(String app, int userHandle) {
393        if (VpnConfig.LEGACY_VPN.equals(app)) {
394            return Process.myUid();
395        }
396        PackageManager pm = mContext.getPackageManager();
397        int result;
398        try {
399            result = pm.getPackageUidAsUser(app, userHandle);
400        } catch (NameNotFoundException e) {
401            result = -1;
402        }
403        return result;
404    }
405
406    public NetworkInfo getNetworkInfo() {
407        return mNetworkInfo;
408    }
409
410    public int getNetId() {
411        return mNetworkAgent != null ? mNetworkAgent.netId : NETID_UNSET;
412    }
413
414    private LinkProperties makeLinkProperties() {
415        boolean allowIPv4 = mConfig.allowIPv4;
416        boolean allowIPv6 = mConfig.allowIPv6;
417
418        LinkProperties lp = new LinkProperties();
419
420        lp.setInterfaceName(mInterface);
421
422        if (mConfig.addresses != null) {
423            for (LinkAddress address : mConfig.addresses) {
424                lp.addLinkAddress(address);
425                allowIPv4 |= address.getAddress() instanceof Inet4Address;
426                allowIPv6 |= address.getAddress() instanceof Inet6Address;
427            }
428        }
429
430        if (mConfig.routes != null) {
431            for (RouteInfo route : mConfig.routes) {
432                lp.addRoute(route);
433                InetAddress address = route.getDestination().getAddress();
434                allowIPv4 |= address instanceof Inet4Address;
435                allowIPv6 |= address instanceof Inet6Address;
436            }
437        }
438
439        if (mConfig.dnsServers != null) {
440            for (String dnsServer : mConfig.dnsServers) {
441                InetAddress address = InetAddress.parseNumericAddress(dnsServer);
442                lp.addDnsServer(address);
443                allowIPv4 |= address instanceof Inet4Address;
444                allowIPv6 |= address instanceof Inet6Address;
445            }
446        }
447
448        if (!allowIPv4) {
449            lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), RTN_UNREACHABLE));
450        }
451        if (!allowIPv6) {
452            lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), RTN_UNREACHABLE));
453        }
454
455        // Concatenate search domains into a string.
456        StringBuilder buffer = new StringBuilder();
457        if (mConfig.searchDomains != null) {
458            for (String domain : mConfig.searchDomains) {
459                buffer.append(domain).append(' ');
460            }
461        }
462        lp.setDomains(buffer.toString().trim());
463
464        // TODO: Stop setting the MTU in jniCreate and set it here.
465
466        return lp;
467    }
468
469    private void agentConnect() {
470        LinkProperties lp = makeLinkProperties();
471
472        if (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute()) {
473            mNetworkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
474        } else {
475            mNetworkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
476        }
477
478        mNetworkInfo.setDetailedState(DetailedState.CONNECTING, null, null);
479
480        NetworkMisc networkMisc = new NetworkMisc();
481        networkMisc.allowBypass = mConfig.allowBypass && !mLockdown;
482
483        long token = Binder.clearCallingIdentity();
484        try {
485            mNetworkAgent = new NetworkAgent(mLooper, mContext, NETWORKTYPE,
486                    mNetworkInfo, mNetworkCapabilities, lp, 0, networkMisc) {
487                            @Override
488                            public void unwanted() {
489                                // We are user controlled, not driven by NetworkRequest.
490                            }
491                        };
492        } finally {
493            Binder.restoreCallingIdentity(token);
494        }
495
496        mVpnUsers = createUserAndRestrictedProfilesRanges(mUserHandle,
497                mConfig.allowedApplications, mConfig.disallowedApplications);
498        mNetworkAgent.addUidRanges(mVpnUsers.toArray(new UidRange[mVpnUsers.size()]));
499
500        mNetworkInfo.setIsAvailable(true);
501        updateState(DetailedState.CONNECTED, "agentConnect");
502    }
503
504    private boolean canHaveRestrictedProfile(int userId) {
505        long token = Binder.clearCallingIdentity();
506        try {
507            return UserManager.get(mContext).canHaveRestrictedProfile(userId);
508        } finally {
509            Binder.restoreCallingIdentity(token);
510        }
511    }
512
513    private void agentDisconnect(NetworkInfo networkInfo, NetworkAgent networkAgent) {
514        networkInfo.setIsAvailable(false);
515        networkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
516        if (networkAgent != null) {
517            networkAgent.sendNetworkInfo(networkInfo);
518        }
519    }
520
521    private void agentDisconnect(NetworkAgent networkAgent) {
522        NetworkInfo networkInfo = new NetworkInfo(mNetworkInfo);
523        agentDisconnect(networkInfo, networkAgent);
524    }
525
526    private void agentDisconnect() {
527        if (mNetworkInfo.isConnected()) {
528            agentDisconnect(mNetworkInfo, mNetworkAgent);
529            mNetworkAgent = null;
530        }
531    }
532
533    /**
534     * Establish a VPN network and return the file descriptor of the VPN
535     * interface. This methods returns {@code null} if the application is
536     * revoked or not prepared.
537     *
538     * @param config The parameters to configure the network.
539     * @return The file descriptor of the VPN interface.
540     */
541    public synchronized ParcelFileDescriptor establish(VpnConfig config) {
542        // Check if the caller is already prepared.
543        UserManager mgr = UserManager.get(mContext);
544        if (Binder.getCallingUid() != mOwnerUID) {
545            return null;
546        }
547        // Check to ensure consent hasn't been revoked since we were prepared.
548        if (!isVpnUserPreConsented(mPackage)) {
549            return null;
550        }
551        // Check if the service is properly declared.
552        Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
553        intent.setClassName(mPackage, config.user);
554        long token = Binder.clearCallingIdentity();
555        try {
556            // Restricted users are not allowed to create VPNs, they are tied to Owner
557            UserInfo user = mgr.getUserInfo(mUserHandle);
558            if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
559                    new UserHandle(mUserHandle))) {
560                throw new SecurityException("Restricted users cannot establish VPNs");
561            }
562
563            ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
564                                                                        null, 0, mUserHandle);
565            if (info == null) {
566                throw new SecurityException("Cannot find " + config.user);
567            }
568            if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
569                throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
570            }
571        } catch (RemoteException e) {
572                throw new SecurityException("Cannot find " + config.user);
573        } finally {
574            Binder.restoreCallingIdentity(token);
575        }
576
577        // Save the old config in case we need to go back.
578        VpnConfig oldConfig = mConfig;
579        String oldInterface = mInterface;
580        Connection oldConnection = mConnection;
581        NetworkAgent oldNetworkAgent = mNetworkAgent;
582        mNetworkAgent = null;
583        Set<UidRange> oldUsers = mVpnUsers;
584
585        // Configure the interface. Abort if any of these steps fails.
586        ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
587        try {
588            updateState(DetailedState.CONNECTING, "establish");
589            String interfaze = jniGetName(tun.getFd());
590
591            // TEMP use the old jni calls until there is support for netd address setting
592            StringBuilder builder = new StringBuilder();
593            for (LinkAddress address : config.addresses) {
594                builder.append(" " + address);
595            }
596            if (jniSetAddresses(interfaze, builder.toString()) < 1) {
597                throw new IllegalArgumentException("At least one address must be specified");
598            }
599            Connection connection = new Connection();
600            if (!mContext.bindServiceAsUser(intent, connection,
601                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
602                    new UserHandle(mUserHandle))) {
603                throw new IllegalStateException("Cannot bind " + config.user);
604            }
605
606            mConnection = connection;
607            mInterface = interfaze;
608
609            // Fill more values.
610            config.user = mPackage;
611            config.interfaze = mInterface;
612            config.startTime = SystemClock.elapsedRealtime();
613            mConfig = config;
614
615            // Set up forwarding and DNS rules.
616            agentConnect();
617
618            if (oldConnection != null) {
619                mContext.unbindService(oldConnection);
620            }
621            // Remove the old tun's user forwarding rules
622            // The new tun's user rules have already been added so they will take over
623            // as rules are deleted. This prevents data leakage as the rules are moved over.
624            agentDisconnect(oldNetworkAgent);
625            if (oldInterface != null && !oldInterface.equals(interfaze)) {
626                jniReset(oldInterface);
627            }
628
629            try {
630                IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
631            } catch (IOException e) {
632                throw new IllegalStateException(
633                        "Cannot set tunnel's fd as blocking=" + config.blocking, e);
634            }
635        } catch (RuntimeException e) {
636            IoUtils.closeQuietly(tun);
637            agentDisconnect();
638            // restore old state
639            mConfig = oldConfig;
640            mConnection = oldConnection;
641            mVpnUsers = oldUsers;
642            mNetworkAgent = oldNetworkAgent;
643            mInterface = oldInterface;
644            throw e;
645        }
646        Log.i(TAG, "Established by " + config.user + " on " + mInterface);
647        return tun;
648    }
649
650    private boolean isRunningLocked() {
651        return mNetworkAgent != null && mInterface != null;
652    }
653
654    // Returns true if the VPN has been established and the calling UID is its owner. Used to check
655    // that a call to mutate VPN state is admissible.
656    private boolean isCallerEstablishedOwnerLocked() {
657        return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
658    }
659
660    // Note: Return type guarantees results are deduped and sorted, which callers require.
661    private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
662        SortedSet<Integer> uids = new TreeSet<Integer>();
663        for (String app : packageNames) {
664            int uid = getAppUid(app, userHandle);
665            if (uid != -1) uids.add(uid);
666        }
667        return uids;
668    }
669
670    /**
671     * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
672     * associated with one user, and any restricted profiles attached to that user.
673     *
674     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
675     * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
676     * in each user and profile will be included.
677     *
678     * @param userHandle The userId to create UID ranges for along with any of its restricted
679     *                   profiles.
680     * @param allowedApplications (optional) whitelist of applications to include.
681     * @param disallowedApplications (optional) blacklist of applications to exclude.
682     */
683    @VisibleForTesting
684    Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
685            @Nullable List<String> allowedApplications,
686            @Nullable List<String> disallowedApplications) {
687        final Set<UidRange> ranges = new ArraySet<>();
688
689        // Assign the top-level user to the set of ranges
690        addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
691
692        // If the user can have restricted profiles, assign all its restricted profiles too
693        if (canHaveRestrictedProfile(userHandle)) {
694            final long token = Binder.clearCallingIdentity();
695            List<UserInfo> users;
696            try {
697                users = UserManager.get(mContext).getUsers(true);
698            } finally {
699                Binder.restoreCallingIdentity(token);
700            }
701            for (UserInfo user : users) {
702                if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
703                    addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
704                }
705            }
706        }
707        return ranges;
708    }
709
710    /**
711     * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
712     * associated with one user.
713     *
714     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
715     * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
716     * in the user will be included.
717     *
718     * @param ranges {@link Set} of {@link UidRange}s to which to add.
719     * @param userHandle The userId to add to {@param ranges}.
720     * @param allowedApplications (optional) whitelist of applications to include.
721     * @param disallowedApplications (optional) blacklist of applications to exclude.
722     */
723    @VisibleForTesting
724    void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
725            @Nullable List<String> allowedApplications,
726            @Nullable List<String> disallowedApplications) {
727        if (allowedApplications != null) {
728            // Add ranges covering all UIDs for allowedApplications.
729            int start = -1, stop = -1;
730            for (int uid : getAppsUids(allowedApplications, userHandle)) {
731                if (start == -1) {
732                    start = uid;
733                } else if (uid != stop + 1) {
734                    ranges.add(new UidRange(start, stop));
735                    start = uid;
736                }
737                stop = uid;
738            }
739            if (start != -1) ranges.add(new UidRange(start, stop));
740        } else if (disallowedApplications != null) {
741            // Add all ranges for user skipping UIDs for disallowedApplications.
742            final UidRange userRange = UidRange.createForUser(userHandle);
743            int start = userRange.start;
744            for (int uid : getAppsUids(disallowedApplications, userHandle)) {
745                if (uid == start) {
746                    start++;
747                } else {
748                    ranges.add(new UidRange(start, uid - 1));
749                    start = uid + 1;
750                }
751            }
752            if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
753        } else {
754            // Add all UIDs for the user.
755            ranges.add(UidRange.createForUser(userHandle));
756        }
757    }
758
759    // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
760    // apply to userHandle.
761    private List<UidRange> uidRangesForUser(int userHandle) {
762        final UidRange userRange = UidRange.createForUser(userHandle);
763        final List<UidRange> ranges = new ArrayList<UidRange>();
764        for (UidRange range : mVpnUsers) {
765            if (userRange.containsRange(range)) {
766                ranges.add(range);
767            }
768        }
769        return ranges;
770    }
771
772    private void removeVpnUserLocked(int userHandle) {
773        if (mVpnUsers == null) {
774            throw new IllegalStateException("VPN is not active");
775        }
776        final List<UidRange> ranges = uidRangesForUser(userHandle);
777        if (mNetworkAgent != null) {
778            mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
779        }
780        mVpnUsers.removeAll(ranges);
781    }
782
783    public void onUserAdded(int userHandle) {
784        // If the user is restricted tie them to the parent user's VPN
785        UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
786        if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
787            synchronized(Vpn.this) {
788                if (mVpnUsers != null) {
789                    try {
790                        addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
791                                mConfig.disallowedApplications);
792                        if (mNetworkAgent != null) {
793                            final List<UidRange> ranges = uidRangesForUser(userHandle);
794                            mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
795                        }
796                    } catch (Exception e) {
797                        Log.wtf(TAG, "Failed to add restricted user to owner", e);
798                    }
799                }
800                if (mAlwaysOn) {
801                    setVpnForcedLocked(mLockdown);
802                }
803            }
804        }
805    }
806
807    public void onUserRemoved(int userHandle) {
808        // clean up if restricted
809        UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
810        if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
811            synchronized(Vpn.this) {
812                if (mVpnUsers != null) {
813                    try {
814                        removeVpnUserLocked(userHandle);
815                    } catch (Exception e) {
816                        Log.wtf(TAG, "Failed to remove restricted user to owner", e);
817                    }
818                }
819                if (mAlwaysOn) {
820                    setVpnForcedLocked(mLockdown);
821                }
822            }
823        }
824    }
825
826    /**
827     * Called when the user associated with this VPN has just been stopped.
828     */
829    public synchronized void onUserStopped() {
830        // Switch off networking lockdown (if it was enabled)
831        setVpnForcedLocked(false);
832        mAlwaysOn = false;
833
834        // Quit any active connections
835        agentDisconnect();
836    }
837
838    /**
839     * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
840     * service app itself, to only sockets that have had {@code protect()} called on them. All
841     * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
842     *
843     * The exception for the VPN UID isn't technically necessary -- setup should use protected
844     * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
845     *
846     * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
847     * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
848     *
849     * @param enforce {@code true} to require that all traffic under the jurisdiction of this
850     *                {@link Vpn} goes through a VPN connection or is blocked until one is
851     *                available, {@code false} to lift the requirement.
852     *
853     * @see #mBlockedUsers
854     */
855    @GuardedBy("this")
856    private void setVpnForcedLocked(boolean enforce) {
857        final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
858        if (enforce) {
859            final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
860                    /* allowedApplications */ null,
861                    /* disallowedApplications */ Collections.singletonList(mPackage));
862
863            removedRanges.removeAll(addedRanges);
864            addedRanges.removeAll(mBlockedUsers);
865
866            setAllowOnlyVpnForUids(false, removedRanges);
867            setAllowOnlyVpnForUids(true, addedRanges);
868        } else {
869            setAllowOnlyVpnForUids(false, removedRanges);
870        }
871    }
872
873    /**
874     * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
875     * to make connections through sockets that have had {@code protect()} called on them.
876     *
877     * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
878     * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
879     *               {@code true}) or to remove.
880     * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
881     *         including added ranges that already existed or removed ones that didn't.
882     */
883    @GuardedBy("this")
884    private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
885        if (ranges.size() == 0) {
886            return true;
887        }
888        final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
889        try {
890            mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
891        } catch (RemoteException | RuntimeException e) {
892            Log.e(TAG, "Updating blocked=" + enforce
893                    + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
894            return false;
895        }
896        if (enforce) {
897            mBlockedUsers.addAll(ranges);
898        } else {
899            mBlockedUsers.removeAll(ranges);
900        }
901        return true;
902    }
903
904    /**
905     * Return the configuration of the currently running VPN.
906     */
907    public VpnConfig getVpnConfig() {
908        enforceControlPermission();
909        return mConfig;
910    }
911
912    @Deprecated
913    public synchronized void interfaceStatusChanged(String iface, boolean up) {
914        try {
915            mObserver.interfaceStatusChanged(iface, up);
916        } catch (RemoteException e) {
917            // ignored; target is local
918        }
919    }
920
921    private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
922        @Override
923        public void interfaceStatusChanged(String interfaze, boolean up) {
924            synchronized (Vpn.this) {
925                if (!up && mLegacyVpnRunner != null) {
926                    mLegacyVpnRunner.check(interfaze);
927                }
928            }
929        }
930
931        @Override
932        public void interfaceRemoved(String interfaze) {
933            synchronized (Vpn.this) {
934                if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
935                    mStatusIntent = null;
936                    mVpnUsers = null;
937                    mConfig = null;
938                    mInterface = null;
939                    if (mConnection != null) {
940                        mContext.unbindService(mConnection);
941                        mConnection = null;
942                        agentDisconnect();
943                    } else if (mLegacyVpnRunner != null) {
944                        mLegacyVpnRunner.exit();
945                        mLegacyVpnRunner = null;
946                    }
947                }
948            }
949        }
950    };
951
952    private void enforceControlPermission() {
953        mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
954    }
955
956    private void enforceControlPermissionOrInternalCaller() {
957        // Require caller to be either an application with CONTROL_VPN permission or a process
958        // in the system server.
959        mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
960                "Unauthorized Caller");
961    }
962
963    private class Connection implements ServiceConnection {
964        private IBinder mService;
965
966        @Override
967        public void onServiceConnected(ComponentName name, IBinder service) {
968            mService = service;
969        }
970
971        @Override
972        public void onServiceDisconnected(ComponentName name) {
973            mService = null;
974        }
975    }
976
977    private void prepareStatusIntent() {
978        final long token = Binder.clearCallingIdentity();
979        try {
980            mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
981        } finally {
982            Binder.restoreCallingIdentity(token);
983        }
984    }
985
986    public synchronized boolean addAddress(String address, int prefixLength) {
987        if (!isCallerEstablishedOwnerLocked()) {
988            return false;
989        }
990        boolean success = jniAddAddress(mInterface, address, prefixLength);
991        mNetworkAgent.sendLinkProperties(makeLinkProperties());
992        return success;
993    }
994
995    public synchronized boolean removeAddress(String address, int prefixLength) {
996        if (!isCallerEstablishedOwnerLocked()) {
997            return false;
998        }
999        boolean success = jniDelAddress(mInterface, address, prefixLength);
1000        mNetworkAgent.sendLinkProperties(makeLinkProperties());
1001        return success;
1002    }
1003
1004    public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1005        if (!isCallerEstablishedOwnerLocked()) {
1006            return false;
1007        }
1008        if (networks == null) {
1009            mConfig.underlyingNetworks = null;
1010        } else {
1011            mConfig.underlyingNetworks = new Network[networks.length];
1012            for (int i = 0; i < networks.length; ++i) {
1013                if (networks[i] == null) {
1014                    mConfig.underlyingNetworks[i] = null;
1015                } else {
1016                    mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1017                }
1018            }
1019        }
1020        return true;
1021    }
1022
1023    public synchronized Network[] getUnderlyingNetworks() {
1024        if (!isRunningLocked()) {
1025            return null;
1026        }
1027        return mConfig.underlyingNetworks;
1028    }
1029
1030    /**
1031     * This method should only be called by ConnectivityService. Because it doesn't
1032     * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1033     */
1034    public synchronized VpnInfo getVpnInfo() {
1035        if (!isRunningLocked()) {
1036            return null;
1037        }
1038
1039        VpnInfo info = new VpnInfo();
1040        info.ownerUid = mOwnerUID;
1041        info.vpnIface = mInterface;
1042        return info;
1043    }
1044
1045    public synchronized boolean appliesToUid(int uid) {
1046        if (!isRunningLocked()) {
1047            return false;
1048        }
1049        for (UidRange uidRange : mVpnUsers) {
1050            if (uidRange.contains(uid)) {
1051                return true;
1052            }
1053        }
1054        return false;
1055    }
1056
1057    /**
1058     * @return {@code true} if {@param uid} is blocked by an always-on VPN.
1059     *         A UID is blocked if it's included in one of the mBlockedUsers ranges and the VPN is
1060     *         not connected, or if the VPN is connected but does not apply to the UID.
1061     *
1062     * @see #mBlockedUsers
1063     */
1064    public synchronized boolean isBlockingUid(int uid) {
1065        if (!mLockdown) {
1066            return false;
1067        }
1068
1069        if (mNetworkInfo.isConnected()) {
1070            return !appliesToUid(uid);
1071        } else {
1072            for (UidRange uidRange : mBlockedUsers) {
1073                if (uidRange.contains(uid)) {
1074                    return true;
1075                }
1076            }
1077            return false;
1078        }
1079    }
1080
1081    private native int jniCreate(int mtu);
1082    private native String jniGetName(int tun);
1083    private native int jniSetAddresses(String interfaze, String addresses);
1084    private native void jniReset(String interfaze);
1085    private native int jniCheck(String interfaze);
1086    private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1087    private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
1088
1089    private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1090        for (RouteInfo route : prop.getAllRoutes()) {
1091            // Currently legacy VPN only works on IPv4.
1092            if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
1093                return route;
1094            }
1095        }
1096
1097        throw new IllegalStateException("Unable to find IPv4 default gateway");
1098    }
1099
1100    /**
1101     * Start legacy VPN, controlling native daemons as needed. Creates a
1102     * secondary thread to perform connection work, returning quickly.
1103     *
1104     * Should only be called to respond to Binder requests as this enforces caller permission. Use
1105     * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1106     * permission check only when the caller is trusted (or the call is initiated by the system).
1107     */
1108    public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
1109        enforceControlPermission();
1110        long token = Binder.clearCallingIdentity();
1111        try {
1112            startLegacyVpnPrivileged(profile, keyStore, egress);
1113        } finally {
1114            Binder.restoreCallingIdentity(token);
1115        }
1116    }
1117
1118    /**
1119     * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1120     * permissions under the assumption that the caller is the system.
1121     *
1122     * Callers are responsible for checking permissions if needed.
1123     */
1124    public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1125            LinkProperties egress) {
1126        UserManager mgr = UserManager.get(mContext);
1127        UserInfo user = mgr.getUserInfo(mUserHandle);
1128        if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1129                    new UserHandle(mUserHandle))) {
1130            throw new SecurityException("Restricted users cannot establish VPNs");
1131        }
1132
1133        final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1134        final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1135        final String iface = ipv4DefaultRoute.getInterface();
1136
1137        // Load certificates.
1138        String privateKey = "";
1139        String userCert = "";
1140        String caCert = "";
1141        String serverCert = "";
1142        if (!profile.ipsecUserCert.isEmpty()) {
1143            privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1144            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
1145            userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1146        }
1147        if (!profile.ipsecCaCert.isEmpty()) {
1148            byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
1149            caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1150        }
1151        if (!profile.ipsecServerCert.isEmpty()) {
1152            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
1153            serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1154        }
1155        if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1156            throw new IllegalStateException("Cannot load credentials");
1157        }
1158
1159        // Prepare arguments for racoon.
1160        String[] racoon = null;
1161        switch (profile.type) {
1162            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1163                racoon = new String[] {
1164                    iface, profile.server, "udppsk", profile.ipsecIdentifier,
1165                    profile.ipsecSecret, "1701",
1166                };
1167                break;
1168            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1169                racoon = new String[] {
1170                    iface, profile.server, "udprsa", privateKey, userCert,
1171                    caCert, serverCert, "1701",
1172                };
1173                break;
1174            case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1175                racoon = new String[] {
1176                    iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1177                    profile.ipsecSecret, profile.username, profile.password, "", gateway,
1178                };
1179                break;
1180            case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1181                racoon = new String[] {
1182                    iface, profile.server, "xauthrsa", privateKey, userCert,
1183                    caCert, serverCert, profile.username, profile.password, "", gateway,
1184                };
1185                break;
1186            case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1187                racoon = new String[] {
1188                    iface, profile.server, "hybridrsa",
1189                    caCert, serverCert, profile.username, profile.password, "", gateway,
1190                };
1191                break;
1192        }
1193
1194        // Prepare arguments for mtpd.
1195        String[] mtpd = null;
1196        switch (profile.type) {
1197            case VpnProfile.TYPE_PPTP:
1198                mtpd = new String[] {
1199                    iface, "pptp", profile.server, "1723",
1200                    "name", profile.username, "password", profile.password,
1201                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1202                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1203                    (profile.mppe ? "+mppe" : "nomppe"),
1204                };
1205                break;
1206            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1207            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1208                mtpd = new String[] {
1209                    iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1210                    "name", profile.username, "password", profile.password,
1211                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1212                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1213                };
1214                break;
1215        }
1216
1217        VpnConfig config = new VpnConfig();
1218        config.legacy = true;
1219        config.user = profile.key;
1220        config.interfaze = iface;
1221        config.session = profile.name;
1222
1223        config.addLegacyRoutes(profile.routes);
1224        if (!profile.dnsServers.isEmpty()) {
1225            config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1226        }
1227        if (!profile.searchDomains.isEmpty()) {
1228            config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1229        }
1230        startLegacyVpn(config, racoon, mtpd);
1231    }
1232
1233    private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
1234        stopLegacyVpnPrivileged();
1235
1236        // Prepare for the new request.
1237        prepareInternal(VpnConfig.LEGACY_VPN);
1238        updateState(DetailedState.CONNECTING, "startLegacyVpn");
1239
1240        // Start a new LegacyVpnRunner and we are done!
1241        mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1242        mLegacyVpnRunner.start();
1243    }
1244
1245    /** Stop legacy VPN. Permissions must be checked by callers. */
1246    public synchronized void stopLegacyVpnPrivileged() {
1247        if (mLegacyVpnRunner != null) {
1248            mLegacyVpnRunner.exit();
1249            mLegacyVpnRunner = null;
1250
1251            synchronized (LegacyVpnRunner.TAG) {
1252                // wait for old thread to completely finish before spinning up
1253                // new instance, otherwise state updates can be out of order.
1254            }
1255        }
1256    }
1257
1258    /**
1259     * Return the information of the current ongoing legacy VPN.
1260     */
1261    public synchronized LegacyVpnInfo getLegacyVpnInfo() {
1262        // Check if the caller is authorized.
1263        enforceControlPermission();
1264        return getLegacyVpnInfoPrivileged();
1265    }
1266
1267    /**
1268     * Return the information of the current ongoing legacy VPN.
1269     * Callers are responsible for checking permissions if needed.
1270     */
1271    public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
1272        if (mLegacyVpnRunner == null) return null;
1273
1274        final LegacyVpnInfo info = new LegacyVpnInfo();
1275        info.key = mConfig.user;
1276        info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
1277        if (mNetworkInfo.isConnected()) {
1278            info.intent = mStatusIntent;
1279        }
1280        return info;
1281    }
1282
1283    public VpnConfig getLegacyVpnConfig() {
1284        if (mLegacyVpnRunner != null) {
1285            return mConfig;
1286        } else {
1287            return null;
1288        }
1289    }
1290
1291    /**
1292     * Bringing up a VPN connection takes time, and that is all this thread
1293     * does. Here we have plenty of time. The only thing we need to take
1294     * care of is responding to interruptions as soon as possible. Otherwise
1295     * requests will be piled up. This can be done in a Handler as a state
1296     * machine, but it is much easier to read in the current form.
1297     */
1298    private class LegacyVpnRunner extends Thread {
1299        private static final String TAG = "LegacyVpnRunner";
1300
1301        private final String[] mDaemons;
1302        private final String[][] mArguments;
1303        private final LocalSocket[] mSockets;
1304        private final String mOuterInterface;
1305        private final AtomicInteger mOuterConnection =
1306                new AtomicInteger(ConnectivityManager.TYPE_NONE);
1307
1308        private long mTimer = -1;
1309
1310        /**
1311         * Watch for the outer connection (passing in the constructor) going away.
1312         */
1313        private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1314            @Override
1315            public void onReceive(Context context, Intent intent) {
1316                if (!mEnableTeardown) return;
1317
1318                if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1319                    if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1320                            ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1321                        NetworkInfo info = (NetworkInfo)intent.getExtra(
1322                                ConnectivityManager.EXTRA_NETWORK_INFO);
1323                        if (info != null && !info.isConnectedOrConnecting()) {
1324                            try {
1325                                mObserver.interfaceStatusChanged(mOuterInterface, false);
1326                            } catch (RemoteException e) {}
1327                        }
1328                    }
1329                }
1330            }
1331        };
1332
1333        public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
1334            super(TAG);
1335            mConfig = config;
1336            mDaemons = new String[] {"racoon", "mtpd"};
1337            // TODO: clear arguments from memory once launched
1338            mArguments = new String[][] {racoon, mtpd};
1339            mSockets = new LocalSocket[mDaemons.length];
1340
1341            // This is the interface which VPN is running on,
1342            // mConfig.interfaze will change to point to OUR
1343            // internal interface soon. TODO - add inner/outer to mconfig
1344            // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
1345            // we will leave the VPN up.  We should check that it's still there/connected after
1346            // registering
1347            mOuterInterface = mConfig.interfaze;
1348
1349            if (!TextUtils.isEmpty(mOuterInterface)) {
1350                final ConnectivityManager cm = ConnectivityManager.from(mContext);
1351                for (Network network : cm.getAllNetworks()) {
1352                    final LinkProperties lp = cm.getLinkProperties(network);
1353                    if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
1354                        final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1355                        if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1356                    }
1357                }
1358            }
1359
1360            IntentFilter filter = new IntentFilter();
1361            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1362            mContext.registerReceiver(mBroadcastReceiver, filter);
1363        }
1364
1365        public void check(String interfaze) {
1366            if (interfaze.equals(mOuterInterface)) {
1367                Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1368                exit();
1369            }
1370        }
1371
1372        public void exit() {
1373            // We assume that everything is reset after stopping the daemons.
1374            interrupt();
1375            for (LocalSocket socket : mSockets) {
1376                IoUtils.closeQuietly(socket);
1377            }
1378            agentDisconnect();
1379            try {
1380                mContext.unregisterReceiver(mBroadcastReceiver);
1381            } catch (IllegalArgumentException e) {}
1382        }
1383
1384        @Override
1385        public void run() {
1386            // Wait for the previous thread since it has been interrupted.
1387            Log.v(TAG, "Waiting");
1388            synchronized (TAG) {
1389                Log.v(TAG, "Executing");
1390                execute();
1391                monitorDaemons();
1392            }
1393        }
1394
1395        private void checkpoint(boolean yield) throws InterruptedException {
1396            long now = SystemClock.elapsedRealtime();
1397            if (mTimer == -1) {
1398                mTimer = now;
1399                Thread.sleep(1);
1400            } else if (now - mTimer <= 60000) {
1401                Thread.sleep(yield ? 200 : 1);
1402            } else {
1403                updateState(DetailedState.FAILED, "checkpoint");
1404                throw new IllegalStateException("Time is up");
1405            }
1406        }
1407
1408        private void execute() {
1409            // Catch all exceptions so we can clean up few things.
1410            boolean initFinished = false;
1411            try {
1412                // Initialize the timer.
1413                checkpoint(false);
1414
1415                // Wait for the daemons to stop.
1416                for (String daemon : mDaemons) {
1417                    while (!SystemService.isStopped(daemon)) {
1418                        checkpoint(true);
1419                    }
1420                }
1421
1422                // Clear the previous state.
1423                File state = new File("/data/misc/vpn/state");
1424                state.delete();
1425                if (state.exists()) {
1426                    throw new IllegalStateException("Cannot delete the state");
1427                }
1428                new File("/data/misc/vpn/abort").delete();
1429                initFinished = true;
1430
1431                // Check if we need to restart any of the daemons.
1432                boolean restart = false;
1433                for (String[] arguments : mArguments) {
1434                    restart = restart || (arguments != null);
1435                }
1436                if (!restart) {
1437                    agentDisconnect();
1438                    return;
1439                }
1440                updateState(DetailedState.CONNECTING, "execute");
1441
1442                // Start the daemon with arguments.
1443                for (int i = 0; i < mDaemons.length; ++i) {
1444                    String[] arguments = mArguments[i];
1445                    if (arguments == null) {
1446                        continue;
1447                    }
1448
1449                    // Start the daemon.
1450                    String daemon = mDaemons[i];
1451                    SystemService.start(daemon);
1452
1453                    // Wait for the daemon to start.
1454                    while (!SystemService.isRunning(daemon)) {
1455                        checkpoint(true);
1456                    }
1457
1458                    // Create the control socket.
1459                    mSockets[i] = new LocalSocket();
1460                    LocalSocketAddress address = new LocalSocketAddress(
1461                            daemon, LocalSocketAddress.Namespace.RESERVED);
1462
1463                    // Wait for the socket to connect.
1464                    while (true) {
1465                        try {
1466                            mSockets[i].connect(address);
1467                            break;
1468                        } catch (Exception e) {
1469                            // ignore
1470                        }
1471                        checkpoint(true);
1472                    }
1473                    mSockets[i].setSoTimeout(500);
1474
1475                    // Send over the arguments.
1476                    OutputStream out = mSockets[i].getOutputStream();
1477                    for (String argument : arguments) {
1478                        byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
1479                        if (bytes.length >= 0xFFFF) {
1480                            throw new IllegalArgumentException("Argument is too large");
1481                        }
1482                        out.write(bytes.length >> 8);
1483                        out.write(bytes.length);
1484                        out.write(bytes);
1485                        checkpoint(false);
1486                    }
1487                    out.write(0xFF);
1488                    out.write(0xFF);
1489                    out.flush();
1490
1491                    // Wait for End-of-File.
1492                    InputStream in = mSockets[i].getInputStream();
1493                    while (true) {
1494                        try {
1495                            if (in.read() == -1) {
1496                                break;
1497                            }
1498                        } catch (Exception e) {
1499                            // ignore
1500                        }
1501                        checkpoint(true);
1502                    }
1503                }
1504
1505                // Wait for the daemons to create the new state.
1506                while (!state.exists()) {
1507                    // Check if a running daemon is dead.
1508                    for (int i = 0; i < mDaemons.length; ++i) {
1509                        String daemon = mDaemons[i];
1510                        if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
1511                            throw new IllegalStateException(daemon + " is dead");
1512                        }
1513                    }
1514                    checkpoint(true);
1515                }
1516
1517                // Now we are connected. Read and parse the new state.
1518                String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
1519                if (parameters.length != 7) {
1520                    throw new IllegalStateException("Cannot parse the state");
1521                }
1522
1523                // Set the interface and the addresses in the config.
1524                mConfig.interfaze = parameters[0].trim();
1525
1526                mConfig.addLegacyAddresses(parameters[1]);
1527                // Set the routes if they are not set in the config.
1528                if (mConfig.routes == null || mConfig.routes.isEmpty()) {
1529                    mConfig.addLegacyRoutes(parameters[2]);
1530                }
1531
1532                // Set the DNS servers if they are not set in the config.
1533                if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
1534                    String dnsServers = parameters[3].trim();
1535                    if (!dnsServers.isEmpty()) {
1536                        mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1537                    }
1538                }
1539
1540                // Set the search domains if they are not set in the config.
1541                if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1542                    String searchDomains = parameters[4].trim();
1543                    if (!searchDomains.isEmpty()) {
1544                        mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1545                    }
1546                }
1547
1548                // Add a throw route for the VPN server endpoint, if one was specified.
1549                String endpoint = parameters[5];
1550                if (!endpoint.isEmpty()) {
1551                    try {
1552                        InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1553                        if (addr instanceof Inet4Address) {
1554                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1555                        } else if (addr instanceof Inet6Address) {
1556                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1557                        } else {
1558                            Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1559                        }
1560                    } catch (IllegalArgumentException e) {
1561                        Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1562                    }
1563                }
1564
1565                // Here is the last step and it must be done synchronously.
1566                synchronized (Vpn.this) {
1567                    // Set the start time
1568                    mConfig.startTime = SystemClock.elapsedRealtime();
1569
1570                    // Check if the thread is interrupted while we are waiting.
1571                    checkpoint(false);
1572
1573                    // Check if the interface is gone while we are waiting.
1574                    if (jniCheck(mConfig.interfaze) == 0) {
1575                        throw new IllegalStateException(mConfig.interfaze + " is gone");
1576                    }
1577
1578                    // Now INetworkManagementEventObserver is watching our back.
1579                    mInterface = mConfig.interfaze;
1580                    prepareStatusIntent();
1581
1582                    agentConnect();
1583
1584                    Log.i(TAG, "Connected!");
1585                }
1586            } catch (Exception e) {
1587                Log.i(TAG, "Aborting", e);
1588                updateState(DetailedState.FAILED, e.getMessage());
1589                exit();
1590            } finally {
1591                // Kill the daemons if they fail to stop.
1592                if (!initFinished) {
1593                    for (String daemon : mDaemons) {
1594                        SystemService.stop(daemon);
1595                    }
1596                }
1597
1598                // Do not leave an unstable state.
1599                if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1600                    agentDisconnect();
1601                }
1602            }
1603        }
1604
1605        /**
1606         * Monitor the daemons we started, moving to disconnected state if the
1607         * underlying services fail.
1608         */
1609        private void monitorDaemons() {
1610            if (!mNetworkInfo.isConnected()) {
1611                return;
1612            }
1613
1614            try {
1615                while (true) {
1616                    Thread.sleep(2000);
1617                    for (int i = 0; i < mDaemons.length; i++) {
1618                        if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1619                            return;
1620                        }
1621                    }
1622                }
1623            } catch (InterruptedException e) {
1624                Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1625            } finally {
1626                for (String daemon : mDaemons) {
1627                    SystemService.stop(daemon);
1628                }
1629
1630                agentDisconnect();
1631            }
1632        }
1633    }
1634}
1635