Vpn.java revision 17e6183b85ba3038acb935aaa01415058b2e6ddd
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 the set of users blocked whilst waiting for VPN to connect includes
1059     *         the UID {@param uid}, {@code false} otherwise.
1060     *
1061     * @see #mBlockedUsers
1062     */
1063    public synchronized boolean isBlockingUid(int uid) {
1064        for (UidRange uidRange : mBlockedUsers) {
1065            if (uidRange.contains(uid)) {
1066                return true;
1067            }
1068        }
1069        return false;
1070    }
1071
1072    private native int jniCreate(int mtu);
1073    private native String jniGetName(int tun);
1074    private native int jniSetAddresses(String interfaze, String addresses);
1075    private native void jniReset(String interfaze);
1076    private native int jniCheck(String interfaze);
1077    private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1078    private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
1079
1080    private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1081        for (RouteInfo route : prop.getAllRoutes()) {
1082            // Currently legacy VPN only works on IPv4.
1083            if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
1084                return route;
1085            }
1086        }
1087
1088        throw new IllegalStateException("Unable to find IPv4 default gateway");
1089    }
1090
1091    /**
1092     * Start legacy VPN, controlling native daemons as needed. Creates a
1093     * secondary thread to perform connection work, returning quickly.
1094     *
1095     * Should only be called to respond to Binder requests as this enforces caller permission. Use
1096     * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1097     * permission check only when the caller is trusted (or the call is initiated by the system).
1098     */
1099    public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
1100        enforceControlPermission();
1101        long token = Binder.clearCallingIdentity();
1102        try {
1103            startLegacyVpnPrivileged(profile, keyStore, egress);
1104        } finally {
1105            Binder.restoreCallingIdentity(token);
1106        }
1107    }
1108
1109    /**
1110     * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1111     * permissions under the assumption that the caller is the system.
1112     *
1113     * Callers are responsible for checking permissions if needed.
1114     */
1115    public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1116            LinkProperties egress) {
1117        UserManager mgr = UserManager.get(mContext);
1118        UserInfo user = mgr.getUserInfo(mUserHandle);
1119        if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1120                    new UserHandle(mUserHandle))) {
1121            throw new SecurityException("Restricted users cannot establish VPNs");
1122        }
1123
1124        final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1125        final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1126        final String iface = ipv4DefaultRoute.getInterface();
1127
1128        // Load certificates.
1129        String privateKey = "";
1130        String userCert = "";
1131        String caCert = "";
1132        String serverCert = "";
1133        if (!profile.ipsecUserCert.isEmpty()) {
1134            privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1135            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
1136            userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1137        }
1138        if (!profile.ipsecCaCert.isEmpty()) {
1139            byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
1140            caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1141        }
1142        if (!profile.ipsecServerCert.isEmpty()) {
1143            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
1144            serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1145        }
1146        if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1147            throw new IllegalStateException("Cannot load credentials");
1148        }
1149
1150        // Prepare arguments for racoon.
1151        String[] racoon = null;
1152        switch (profile.type) {
1153            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1154                racoon = new String[] {
1155                    iface, profile.server, "udppsk", profile.ipsecIdentifier,
1156                    profile.ipsecSecret, "1701",
1157                };
1158                break;
1159            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1160                racoon = new String[] {
1161                    iface, profile.server, "udprsa", privateKey, userCert,
1162                    caCert, serverCert, "1701",
1163                };
1164                break;
1165            case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1166                racoon = new String[] {
1167                    iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1168                    profile.ipsecSecret, profile.username, profile.password, "", gateway,
1169                };
1170                break;
1171            case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1172                racoon = new String[] {
1173                    iface, profile.server, "xauthrsa", privateKey, userCert,
1174                    caCert, serverCert, profile.username, profile.password, "", gateway,
1175                };
1176                break;
1177            case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1178                racoon = new String[] {
1179                    iface, profile.server, "hybridrsa",
1180                    caCert, serverCert, profile.username, profile.password, "", gateway,
1181                };
1182                break;
1183        }
1184
1185        // Prepare arguments for mtpd.
1186        String[] mtpd = null;
1187        switch (profile.type) {
1188            case VpnProfile.TYPE_PPTP:
1189                mtpd = new String[] {
1190                    iface, "pptp", profile.server, "1723",
1191                    "name", profile.username, "password", profile.password,
1192                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1193                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1194                    (profile.mppe ? "+mppe" : "nomppe"),
1195                };
1196                break;
1197            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1198            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1199                mtpd = new String[] {
1200                    iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1201                    "name", profile.username, "password", profile.password,
1202                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1203                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1204                };
1205                break;
1206        }
1207
1208        VpnConfig config = new VpnConfig();
1209        config.legacy = true;
1210        config.user = profile.key;
1211        config.interfaze = iface;
1212        config.session = profile.name;
1213
1214        config.addLegacyRoutes(profile.routes);
1215        if (!profile.dnsServers.isEmpty()) {
1216            config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1217        }
1218        if (!profile.searchDomains.isEmpty()) {
1219            config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1220        }
1221        startLegacyVpn(config, racoon, mtpd);
1222    }
1223
1224    private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
1225        stopLegacyVpnPrivileged();
1226
1227        // Prepare for the new request.
1228        prepareInternal(VpnConfig.LEGACY_VPN);
1229        updateState(DetailedState.CONNECTING, "startLegacyVpn");
1230
1231        // Start a new LegacyVpnRunner and we are done!
1232        mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1233        mLegacyVpnRunner.start();
1234    }
1235
1236    /** Stop legacy VPN. Permissions must be checked by callers. */
1237    public synchronized void stopLegacyVpnPrivileged() {
1238        if (mLegacyVpnRunner != null) {
1239            mLegacyVpnRunner.exit();
1240            mLegacyVpnRunner = null;
1241
1242            synchronized (LegacyVpnRunner.TAG) {
1243                // wait for old thread to completely finish before spinning up
1244                // new instance, otherwise state updates can be out of order.
1245            }
1246        }
1247    }
1248
1249    /**
1250     * Return the information of the current ongoing legacy VPN.
1251     */
1252    public synchronized LegacyVpnInfo getLegacyVpnInfo() {
1253        // Check if the caller is authorized.
1254        enforceControlPermission();
1255        return getLegacyVpnInfoPrivileged();
1256    }
1257
1258    /**
1259     * Return the information of the current ongoing legacy VPN.
1260     * Callers are responsible for checking permissions if needed.
1261     */
1262    public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
1263        if (mLegacyVpnRunner == null) return null;
1264
1265        final LegacyVpnInfo info = new LegacyVpnInfo();
1266        info.key = mConfig.user;
1267        info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
1268        if (mNetworkInfo.isConnected()) {
1269            info.intent = mStatusIntent;
1270        }
1271        return info;
1272    }
1273
1274    public VpnConfig getLegacyVpnConfig() {
1275        if (mLegacyVpnRunner != null) {
1276            return mConfig;
1277        } else {
1278            return null;
1279        }
1280    }
1281
1282    /**
1283     * Bringing up a VPN connection takes time, and that is all this thread
1284     * does. Here we have plenty of time. The only thing we need to take
1285     * care of is responding to interruptions as soon as possible. Otherwise
1286     * requests will be piled up. This can be done in a Handler as a state
1287     * machine, but it is much easier to read in the current form.
1288     */
1289    private class LegacyVpnRunner extends Thread {
1290        private static final String TAG = "LegacyVpnRunner";
1291
1292        private final String[] mDaemons;
1293        private final String[][] mArguments;
1294        private final LocalSocket[] mSockets;
1295        private final String mOuterInterface;
1296        private final AtomicInteger mOuterConnection =
1297                new AtomicInteger(ConnectivityManager.TYPE_NONE);
1298
1299        private long mTimer = -1;
1300
1301        /**
1302         * Watch for the outer connection (passing in the constructor) going away.
1303         */
1304        private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1305            @Override
1306            public void onReceive(Context context, Intent intent) {
1307                if (!mEnableTeardown) return;
1308
1309                if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1310                    if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1311                            ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1312                        NetworkInfo info = (NetworkInfo)intent.getExtra(
1313                                ConnectivityManager.EXTRA_NETWORK_INFO);
1314                        if (info != null && !info.isConnectedOrConnecting()) {
1315                            try {
1316                                mObserver.interfaceStatusChanged(mOuterInterface, false);
1317                            } catch (RemoteException e) {}
1318                        }
1319                    }
1320                }
1321            }
1322        };
1323
1324        public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
1325            super(TAG);
1326            mConfig = config;
1327            mDaemons = new String[] {"racoon", "mtpd"};
1328            // TODO: clear arguments from memory once launched
1329            mArguments = new String[][] {racoon, mtpd};
1330            mSockets = new LocalSocket[mDaemons.length];
1331
1332            // This is the interface which VPN is running on,
1333            // mConfig.interfaze will change to point to OUR
1334            // internal interface soon. TODO - add inner/outer to mconfig
1335            // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
1336            // we will leave the VPN up.  We should check that it's still there/connected after
1337            // registering
1338            mOuterInterface = mConfig.interfaze;
1339
1340            if (!TextUtils.isEmpty(mOuterInterface)) {
1341                final ConnectivityManager cm = ConnectivityManager.from(mContext);
1342                for (Network network : cm.getAllNetworks()) {
1343                    final LinkProperties lp = cm.getLinkProperties(network);
1344                    if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
1345                        final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1346                        if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1347                    }
1348                }
1349            }
1350
1351            IntentFilter filter = new IntentFilter();
1352            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1353            mContext.registerReceiver(mBroadcastReceiver, filter);
1354        }
1355
1356        public void check(String interfaze) {
1357            if (interfaze.equals(mOuterInterface)) {
1358                Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1359                exit();
1360            }
1361        }
1362
1363        public void exit() {
1364            // We assume that everything is reset after stopping the daemons.
1365            interrupt();
1366            for (LocalSocket socket : mSockets) {
1367                IoUtils.closeQuietly(socket);
1368            }
1369            agentDisconnect();
1370            try {
1371                mContext.unregisterReceiver(mBroadcastReceiver);
1372            } catch (IllegalArgumentException e) {}
1373        }
1374
1375        @Override
1376        public void run() {
1377            // Wait for the previous thread since it has been interrupted.
1378            Log.v(TAG, "Waiting");
1379            synchronized (TAG) {
1380                Log.v(TAG, "Executing");
1381                execute();
1382                monitorDaemons();
1383            }
1384        }
1385
1386        private void checkpoint(boolean yield) throws InterruptedException {
1387            long now = SystemClock.elapsedRealtime();
1388            if (mTimer == -1) {
1389                mTimer = now;
1390                Thread.sleep(1);
1391            } else if (now - mTimer <= 60000) {
1392                Thread.sleep(yield ? 200 : 1);
1393            } else {
1394                updateState(DetailedState.FAILED, "checkpoint");
1395                throw new IllegalStateException("Time is up");
1396            }
1397        }
1398
1399        private void execute() {
1400            // Catch all exceptions so we can clean up few things.
1401            boolean initFinished = false;
1402            try {
1403                // Initialize the timer.
1404                checkpoint(false);
1405
1406                // Wait for the daemons to stop.
1407                for (String daemon : mDaemons) {
1408                    while (!SystemService.isStopped(daemon)) {
1409                        checkpoint(true);
1410                    }
1411                }
1412
1413                // Clear the previous state.
1414                File state = new File("/data/misc/vpn/state");
1415                state.delete();
1416                if (state.exists()) {
1417                    throw new IllegalStateException("Cannot delete the state");
1418                }
1419                new File("/data/misc/vpn/abort").delete();
1420                initFinished = true;
1421
1422                // Check if we need to restart any of the daemons.
1423                boolean restart = false;
1424                for (String[] arguments : mArguments) {
1425                    restart = restart || (arguments != null);
1426                }
1427                if (!restart) {
1428                    agentDisconnect();
1429                    return;
1430                }
1431                updateState(DetailedState.CONNECTING, "execute");
1432
1433                // Start the daemon with arguments.
1434                for (int i = 0; i < mDaemons.length; ++i) {
1435                    String[] arguments = mArguments[i];
1436                    if (arguments == null) {
1437                        continue;
1438                    }
1439
1440                    // Start the daemon.
1441                    String daemon = mDaemons[i];
1442                    SystemService.start(daemon);
1443
1444                    // Wait for the daemon to start.
1445                    while (!SystemService.isRunning(daemon)) {
1446                        checkpoint(true);
1447                    }
1448
1449                    // Create the control socket.
1450                    mSockets[i] = new LocalSocket();
1451                    LocalSocketAddress address = new LocalSocketAddress(
1452                            daemon, LocalSocketAddress.Namespace.RESERVED);
1453
1454                    // Wait for the socket to connect.
1455                    while (true) {
1456                        try {
1457                            mSockets[i].connect(address);
1458                            break;
1459                        } catch (Exception e) {
1460                            // ignore
1461                        }
1462                        checkpoint(true);
1463                    }
1464                    mSockets[i].setSoTimeout(500);
1465
1466                    // Send over the arguments.
1467                    OutputStream out = mSockets[i].getOutputStream();
1468                    for (String argument : arguments) {
1469                        byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
1470                        if (bytes.length >= 0xFFFF) {
1471                            throw new IllegalArgumentException("Argument is too large");
1472                        }
1473                        out.write(bytes.length >> 8);
1474                        out.write(bytes.length);
1475                        out.write(bytes);
1476                        checkpoint(false);
1477                    }
1478                    out.write(0xFF);
1479                    out.write(0xFF);
1480                    out.flush();
1481
1482                    // Wait for End-of-File.
1483                    InputStream in = mSockets[i].getInputStream();
1484                    while (true) {
1485                        try {
1486                            if (in.read() == -1) {
1487                                break;
1488                            }
1489                        } catch (Exception e) {
1490                            // ignore
1491                        }
1492                        checkpoint(true);
1493                    }
1494                }
1495
1496                // Wait for the daemons to create the new state.
1497                while (!state.exists()) {
1498                    // Check if a running daemon is dead.
1499                    for (int i = 0; i < mDaemons.length; ++i) {
1500                        String daemon = mDaemons[i];
1501                        if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
1502                            throw new IllegalStateException(daemon + " is dead");
1503                        }
1504                    }
1505                    checkpoint(true);
1506                }
1507
1508                // Now we are connected. Read and parse the new state.
1509                String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
1510                if (parameters.length != 7) {
1511                    throw new IllegalStateException("Cannot parse the state");
1512                }
1513
1514                // Set the interface and the addresses in the config.
1515                mConfig.interfaze = parameters[0].trim();
1516
1517                mConfig.addLegacyAddresses(parameters[1]);
1518                // Set the routes if they are not set in the config.
1519                if (mConfig.routes == null || mConfig.routes.isEmpty()) {
1520                    mConfig.addLegacyRoutes(parameters[2]);
1521                }
1522
1523                // Set the DNS servers if they are not set in the config.
1524                if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
1525                    String dnsServers = parameters[3].trim();
1526                    if (!dnsServers.isEmpty()) {
1527                        mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1528                    }
1529                }
1530
1531                // Set the search domains if they are not set in the config.
1532                if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1533                    String searchDomains = parameters[4].trim();
1534                    if (!searchDomains.isEmpty()) {
1535                        mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1536                    }
1537                }
1538
1539                // Add a throw route for the VPN server endpoint, if one was specified.
1540                String endpoint = parameters[5];
1541                if (!endpoint.isEmpty()) {
1542                    try {
1543                        InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1544                        if (addr instanceof Inet4Address) {
1545                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1546                        } else if (addr instanceof Inet6Address) {
1547                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1548                        } else {
1549                            Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1550                        }
1551                    } catch (IllegalArgumentException e) {
1552                        Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1553                    }
1554                }
1555
1556                // Here is the last step and it must be done synchronously.
1557                synchronized (Vpn.this) {
1558                    // Set the start time
1559                    mConfig.startTime = SystemClock.elapsedRealtime();
1560
1561                    // Check if the thread is interrupted while we are waiting.
1562                    checkpoint(false);
1563
1564                    // Check if the interface is gone while we are waiting.
1565                    if (jniCheck(mConfig.interfaze) == 0) {
1566                        throw new IllegalStateException(mConfig.interfaze + " is gone");
1567                    }
1568
1569                    // Now INetworkManagementEventObserver is watching our back.
1570                    mInterface = mConfig.interfaze;
1571                    prepareStatusIntent();
1572
1573                    agentConnect();
1574
1575                    Log.i(TAG, "Connected!");
1576                }
1577            } catch (Exception e) {
1578                Log.i(TAG, "Aborting", e);
1579                updateState(DetailedState.FAILED, e.getMessage());
1580                exit();
1581            } finally {
1582                // Kill the daemons if they fail to stop.
1583                if (!initFinished) {
1584                    for (String daemon : mDaemons) {
1585                        SystemService.stop(daemon);
1586                    }
1587                }
1588
1589                // Do not leave an unstable state.
1590                if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1591                    agentDisconnect();
1592                }
1593            }
1594        }
1595
1596        /**
1597         * Monitor the daemons we started, moving to disconnected state if the
1598         * underlying services fail.
1599         */
1600        private void monitorDaemons() {
1601            if (!mNetworkInfo.isConnected()) {
1602                return;
1603            }
1604
1605            try {
1606                while (true) {
1607                    Thread.sleep(2000);
1608                    for (int i = 0; i < mDaemons.length; i++) {
1609                        if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1610                            return;
1611                        }
1612                    }
1613                }
1614            } catch (InterruptedException e) {
1615                Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1616            } finally {
1617                for (String daemon : mDaemons) {
1618                    SystemService.stop(daemon);
1619                }
1620
1621                agentDisconnect();
1622            }
1623        }
1624    }
1625}
1626