Vpn.java revision 628ae0d84180c5f7c52725e02506021e532ed252
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()) {
559                throw new SecurityException("Restricted users cannot establish VPNs");
560            }
561
562            ResolveInfo info = AppGlobals.getPackageManager().resolveService(intent,
563                                                                        null, 0, mUserHandle);
564            if (info == null) {
565                throw new SecurityException("Cannot find " + config.user);
566            }
567            if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
568                throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
569            }
570        } catch (RemoteException e) {
571                throw new SecurityException("Cannot find " + config.user);
572        } finally {
573            Binder.restoreCallingIdentity(token);
574        }
575
576        // Save the old config in case we need to go back.
577        VpnConfig oldConfig = mConfig;
578        String oldInterface = mInterface;
579        Connection oldConnection = mConnection;
580        NetworkAgent oldNetworkAgent = mNetworkAgent;
581        mNetworkAgent = null;
582        Set<UidRange> oldUsers = mVpnUsers;
583
584        // Configure the interface. Abort if any of these steps fails.
585        ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
586        try {
587            updateState(DetailedState.CONNECTING, "establish");
588            String interfaze = jniGetName(tun.getFd());
589
590            // TEMP use the old jni calls until there is support for netd address setting
591            StringBuilder builder = new StringBuilder();
592            for (LinkAddress address : config.addresses) {
593                builder.append(" " + address);
594            }
595            if (jniSetAddresses(interfaze, builder.toString()) < 1) {
596                throw new IllegalArgumentException("At least one address must be specified");
597            }
598            Connection connection = new Connection();
599            if (!mContext.bindServiceAsUser(intent, connection,
600                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
601                    new UserHandle(mUserHandle))) {
602                throw new IllegalStateException("Cannot bind " + config.user);
603            }
604
605            mConnection = connection;
606            mInterface = interfaze;
607
608            // Fill more values.
609            config.user = mPackage;
610            config.interfaze = mInterface;
611            config.startTime = SystemClock.elapsedRealtime();
612            mConfig = config;
613
614            // Set up forwarding and DNS rules.
615            agentConnect();
616
617            if (oldConnection != null) {
618                mContext.unbindService(oldConnection);
619            }
620            // Remove the old tun's user forwarding rules
621            // The new tun's user rules have already been added so they will take over
622            // as rules are deleted. This prevents data leakage as the rules are moved over.
623            agentDisconnect(oldNetworkAgent);
624            if (oldInterface != null && !oldInterface.equals(interfaze)) {
625                jniReset(oldInterface);
626            }
627
628            try {
629                IoUtils.setBlocking(tun.getFileDescriptor(), config.blocking);
630            } catch (IOException e) {
631                throw new IllegalStateException(
632                        "Cannot set tunnel's fd as blocking=" + config.blocking, e);
633            }
634        } catch (RuntimeException e) {
635            IoUtils.closeQuietly(tun);
636            agentDisconnect();
637            // restore old state
638            mConfig = oldConfig;
639            mConnection = oldConnection;
640            mVpnUsers = oldUsers;
641            mNetworkAgent = oldNetworkAgent;
642            mInterface = oldInterface;
643            throw e;
644        }
645        Log.i(TAG, "Established by " + config.user + " on " + mInterface);
646        return tun;
647    }
648
649    private boolean isRunningLocked() {
650        return mNetworkAgent != null && mInterface != null;
651    }
652
653    // Returns true if the VPN has been established and the calling UID is its owner. Used to check
654    // that a call to mutate VPN state is admissible.
655    private boolean isCallerEstablishedOwnerLocked() {
656        return isRunningLocked() && Binder.getCallingUid() == mOwnerUID;
657    }
658
659    // Note: Return type guarantees results are deduped and sorted, which callers require.
660    private SortedSet<Integer> getAppsUids(List<String> packageNames, int userHandle) {
661        SortedSet<Integer> uids = new TreeSet<Integer>();
662        for (String app : packageNames) {
663            int uid = getAppUid(app, userHandle);
664            if (uid != -1) uids.add(uid);
665        }
666        return uids;
667    }
668
669    /**
670     * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
671     * associated with one user, and any restricted profiles attached to that user.
672     *
673     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
674     * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
675     * in each user and profile will be included.
676     *
677     * @param userHandle The userId to create UID ranges for along with any of its restricted
678     *                   profiles.
679     * @param allowedApplications (optional) whitelist of applications to include.
680     * @param disallowedApplications (optional) blacklist of applications to exclude.
681     */
682    @VisibleForTesting
683    Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
684            @Nullable List<String> allowedApplications,
685            @Nullable List<String> disallowedApplications) {
686        final Set<UidRange> ranges = new ArraySet<>();
687
688        // Assign the top-level user to the set of ranges
689        addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);
690
691        // If the user can have restricted profiles, assign all its restricted profiles too
692        if (canHaveRestrictedProfile(userHandle)) {
693            final long token = Binder.clearCallingIdentity();
694            List<UserInfo> users;
695            try {
696                users = UserManager.get(mContext).getUsers(true);
697            } finally {
698                Binder.restoreCallingIdentity(token);
699            }
700            for (UserInfo user : users) {
701                if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
702                    addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
703                }
704            }
705        }
706        return ranges;
707    }
708
709    /**
710     * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
711     * associated with one user.
712     *
713     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
714     * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
715     * in the user will be included.
716     *
717     * @param ranges {@link Set} of {@link UidRange}s to which to add.
718     * @param userHandle The userId to add to {@param ranges}.
719     * @param allowedApplications (optional) whitelist of applications to include.
720     * @param disallowedApplications (optional) blacklist of applications to exclude.
721     */
722    @VisibleForTesting
723    void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userHandle,
724            @Nullable List<String> allowedApplications,
725            @Nullable List<String> disallowedApplications) {
726        if (allowedApplications != null) {
727            // Add ranges covering all UIDs for allowedApplications.
728            int start = -1, stop = -1;
729            for (int uid : getAppsUids(allowedApplications, userHandle)) {
730                if (start == -1) {
731                    start = uid;
732                } else if (uid != stop + 1) {
733                    ranges.add(new UidRange(start, stop));
734                    start = uid;
735                }
736                stop = uid;
737            }
738            if (start != -1) ranges.add(new UidRange(start, stop));
739        } else if (disallowedApplications != null) {
740            // Add all ranges for user skipping UIDs for disallowedApplications.
741            final UidRange userRange = UidRange.createForUser(userHandle);
742            int start = userRange.start;
743            for (int uid : getAppsUids(disallowedApplications, userHandle)) {
744                if (uid == start) {
745                    start++;
746                } else {
747                    ranges.add(new UidRange(start, uid - 1));
748                    start = uid + 1;
749                }
750            }
751            if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
752        } else {
753            // Add all UIDs for the user.
754            ranges.add(UidRange.createForUser(userHandle));
755        }
756    }
757
758    // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
759    // apply to userHandle.
760    private List<UidRange> uidRangesForUser(int userHandle) {
761        final UidRange userRange = UidRange.createForUser(userHandle);
762        final List<UidRange> ranges = new ArrayList<UidRange>();
763        for (UidRange range : mVpnUsers) {
764            if (userRange.containsRange(range)) {
765                ranges.add(range);
766            }
767        }
768        return ranges;
769    }
770
771    private void removeVpnUserLocked(int userHandle) {
772        if (mVpnUsers == null) {
773            throw new IllegalStateException("VPN is not active");
774        }
775        final List<UidRange> ranges = uidRangesForUser(userHandle);
776        if (mNetworkAgent != null) {
777            mNetworkAgent.removeUidRanges(ranges.toArray(new UidRange[ranges.size()]));
778        }
779        mVpnUsers.removeAll(ranges);
780    }
781
782    public void onUserAdded(int userHandle) {
783        // If the user is restricted tie them to the parent user's VPN
784        UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
785        if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
786            synchronized(Vpn.this) {
787                if (mVpnUsers != null) {
788                    try {
789                        addUserToRanges(mVpnUsers, userHandle, mConfig.allowedApplications,
790                                mConfig.disallowedApplications);
791                        if (mNetworkAgent != null) {
792                            final List<UidRange> ranges = uidRangesForUser(userHandle);
793                            mNetworkAgent.addUidRanges(ranges.toArray(new UidRange[ranges.size()]));
794                        }
795                    } catch (Exception e) {
796                        Log.wtf(TAG, "Failed to add restricted user to owner", e);
797                    }
798                }
799                if (mAlwaysOn) {
800                    setVpnForcedLocked(mLockdown);
801                }
802            }
803        }
804    }
805
806    public void onUserRemoved(int userHandle) {
807        // clean up if restricted
808        UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
809        if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
810            synchronized(Vpn.this) {
811                if (mVpnUsers != null) {
812                    try {
813                        removeVpnUserLocked(userHandle);
814                    } catch (Exception e) {
815                        Log.wtf(TAG, "Failed to remove restricted user to owner", e);
816                    }
817                }
818                if (mAlwaysOn) {
819                    setVpnForcedLocked(mLockdown);
820                }
821            }
822        }
823    }
824
825    /**
826     * Called when the user associated with this VPN has just been stopped.
827     */
828    public synchronized void onUserStopped() {
829        // Switch off networking lockdown (if it was enabled)
830        setVpnForcedLocked(false);
831        mAlwaysOn = false;
832
833        // Quit any active connections
834        agentDisconnect();
835    }
836
837    /**
838     * Restrict network access from all UIDs affected by this {@link Vpn}, apart from the VPN
839     * service app itself, to only sockets that have had {@code protect()} called on them. All
840     * non-VPN traffic is blocked via a {@code PROHIBIT} response from the kernel.
841     *
842     * The exception for the VPN UID isn't technically necessary -- setup should use protected
843     * sockets -- but in practice it saves apps that don't protect their sockets from breaking.
844     *
845     * Calling multiple times with {@param enforce} = {@code true} will recreate the set of UIDs to
846     * block every time, and if anything has changed update using {@link #setAllowOnlyVpnForUids}.
847     *
848     * @param enforce {@code true} to require that all traffic under the jurisdiction of this
849     *                {@link Vpn} goes through a VPN connection or is blocked until one is
850     *                available, {@code false} to lift the requirement.
851     *
852     * @see #mBlockedUsers
853     */
854    @GuardedBy("this")
855    private void setVpnForcedLocked(boolean enforce) {
856        final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
857        if (enforce) {
858            final Set<UidRange> addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
859                    /* allowedApplications */ null,
860                    /* disallowedApplications */ Collections.singletonList(mPackage));
861
862            removedRanges.removeAll(addedRanges);
863            addedRanges.removeAll(mBlockedUsers);
864
865            setAllowOnlyVpnForUids(false, removedRanges);
866            setAllowOnlyVpnForUids(true, addedRanges);
867        } else {
868            setAllowOnlyVpnForUids(false, removedRanges);
869        }
870    }
871
872    /**
873     * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
874     * to make connections through sockets that have had {@code protect()} called on them.
875     *
876     * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
877     * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
878     *               {@code true}) or to remove.
879     * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
880     *         including added ranges that already existed or removed ones that didn't.
881     */
882    @GuardedBy("this")
883    private boolean setAllowOnlyVpnForUids(boolean enforce, Collection<UidRange> ranges) {
884        if (ranges.size() == 0) {
885            return true;
886        }
887        final UidRange[] rangesArray = ranges.toArray(new UidRange[ranges.size()]);
888        try {
889            mNetd.setAllowOnlyVpnForUids(enforce, rangesArray);
890        } catch (RemoteException | RuntimeException e) {
891            Log.e(TAG, "Updating blocked=" + enforce
892                    + " for UIDs " + Arrays.toString(ranges.toArray()) + " failed", e);
893            return false;
894        }
895        if (enforce) {
896            mBlockedUsers.addAll(ranges);
897        } else {
898            mBlockedUsers.removeAll(ranges);
899        }
900        return true;
901    }
902
903    /**
904     * Return the configuration of the currently running VPN.
905     */
906    public VpnConfig getVpnConfig() {
907        enforceControlPermission();
908        return mConfig;
909    }
910
911    @Deprecated
912    public synchronized void interfaceStatusChanged(String iface, boolean up) {
913        try {
914            mObserver.interfaceStatusChanged(iface, up);
915        } catch (RemoteException e) {
916            // ignored; target is local
917        }
918    }
919
920    private INetworkManagementEventObserver mObserver = new BaseNetworkObserver() {
921        @Override
922        public void interfaceStatusChanged(String interfaze, boolean up) {
923            synchronized (Vpn.this) {
924                if (!up && mLegacyVpnRunner != null) {
925                    mLegacyVpnRunner.check(interfaze);
926                }
927            }
928        }
929
930        @Override
931        public void interfaceRemoved(String interfaze) {
932            synchronized (Vpn.this) {
933                if (interfaze.equals(mInterface) && jniCheck(interfaze) == 0) {
934                    mStatusIntent = null;
935                    mVpnUsers = null;
936                    mConfig = null;
937                    mInterface = null;
938                    if (mConnection != null) {
939                        mContext.unbindService(mConnection);
940                        mConnection = null;
941                        agentDisconnect();
942                    } else if (mLegacyVpnRunner != null) {
943                        mLegacyVpnRunner.exit();
944                        mLegacyVpnRunner = null;
945                    }
946                }
947            }
948        }
949    };
950
951    private void enforceControlPermission() {
952        mContext.enforceCallingPermission(Manifest.permission.CONTROL_VPN, "Unauthorized Caller");
953    }
954
955    private void enforceControlPermissionOrInternalCaller() {
956        // Require caller to be either an application with CONTROL_VPN permission or a process
957        // in the system server.
958        mContext.enforceCallingOrSelfPermission(Manifest.permission.CONTROL_VPN,
959                "Unauthorized Caller");
960    }
961
962    private class Connection implements ServiceConnection {
963        private IBinder mService;
964
965        @Override
966        public void onServiceConnected(ComponentName name, IBinder service) {
967            mService = service;
968        }
969
970        @Override
971        public void onServiceDisconnected(ComponentName name) {
972            mService = null;
973        }
974    }
975
976    private void prepareStatusIntent() {
977        final long token = Binder.clearCallingIdentity();
978        try {
979            mStatusIntent = VpnConfig.getIntentForStatusPanel(mContext);
980        } finally {
981            Binder.restoreCallingIdentity(token);
982        }
983    }
984
985    public synchronized boolean addAddress(String address, int prefixLength) {
986        if (!isCallerEstablishedOwnerLocked()) {
987            return false;
988        }
989        boolean success = jniAddAddress(mInterface, address, prefixLength);
990        mNetworkAgent.sendLinkProperties(makeLinkProperties());
991        return success;
992    }
993
994    public synchronized boolean removeAddress(String address, int prefixLength) {
995        if (!isCallerEstablishedOwnerLocked()) {
996            return false;
997        }
998        boolean success = jniDelAddress(mInterface, address, prefixLength);
999        mNetworkAgent.sendLinkProperties(makeLinkProperties());
1000        return success;
1001    }
1002
1003    public synchronized boolean setUnderlyingNetworks(Network[] networks) {
1004        if (!isCallerEstablishedOwnerLocked()) {
1005            return false;
1006        }
1007        if (networks == null) {
1008            mConfig.underlyingNetworks = null;
1009        } else {
1010            mConfig.underlyingNetworks = new Network[networks.length];
1011            for (int i = 0; i < networks.length; ++i) {
1012                if (networks[i] == null) {
1013                    mConfig.underlyingNetworks[i] = null;
1014                } else {
1015                    mConfig.underlyingNetworks[i] = new Network(networks[i].netId);
1016                }
1017            }
1018        }
1019        return true;
1020    }
1021
1022    public synchronized Network[] getUnderlyingNetworks() {
1023        if (!isRunningLocked()) {
1024            return null;
1025        }
1026        return mConfig.underlyingNetworks;
1027    }
1028
1029    /**
1030     * This method should only be called by ConnectivityService. Because it doesn't
1031     * have enough data to fill VpnInfo.primaryUnderlyingIface field.
1032     */
1033    public synchronized VpnInfo getVpnInfo() {
1034        if (!isRunningLocked()) {
1035            return null;
1036        }
1037
1038        VpnInfo info = new VpnInfo();
1039        info.ownerUid = mOwnerUID;
1040        info.vpnIface = mInterface;
1041        return info;
1042    }
1043
1044    public synchronized boolean appliesToUid(int uid) {
1045        if (!isRunningLocked()) {
1046            return false;
1047        }
1048        for (UidRange uidRange : mVpnUsers) {
1049            if (uidRange.contains(uid)) {
1050                return true;
1051            }
1052        }
1053        return false;
1054    }
1055
1056    /**
1057     * @return {@code true} if the set of users blocked whilst waiting for VPN to connect includes
1058     *         the UID {@param uid}, {@code false} otherwise.
1059     *
1060     * @see #mBlockedUsers
1061     */
1062    public synchronized boolean isBlockingUid(int uid) {
1063        for (UidRange uidRange : mBlockedUsers) {
1064            if (uidRange.contains(uid)) {
1065                return true;
1066            }
1067        }
1068        return false;
1069    }
1070
1071    private native int jniCreate(int mtu);
1072    private native String jniGetName(int tun);
1073    private native int jniSetAddresses(String interfaze, String addresses);
1074    private native void jniReset(String interfaze);
1075    private native int jniCheck(String interfaze);
1076    private native boolean jniAddAddress(String interfaze, String address, int prefixLen);
1077    private native boolean jniDelAddress(String interfaze, String address, int prefixLen);
1078
1079    private static RouteInfo findIPv4DefaultRoute(LinkProperties prop) {
1080        for (RouteInfo route : prop.getAllRoutes()) {
1081            // Currently legacy VPN only works on IPv4.
1082            if (route.isDefaultRoute() && route.getGateway() instanceof Inet4Address) {
1083                return route;
1084            }
1085        }
1086
1087        throw new IllegalStateException("Unable to find IPv4 default gateway");
1088    }
1089
1090    /**
1091     * Start legacy VPN, controlling native daemons as needed. Creates a
1092     * secondary thread to perform connection work, returning quickly.
1093     *
1094     * Should only be called to respond to Binder requests as this enforces caller permission. Use
1095     * {@link #startLegacyVpnPrivileged(VpnProfile, KeyStore, LinkProperties)} to skip the
1096     * permission check only when the caller is trusted (or the call is initiated by the system).
1097     */
1098    public void startLegacyVpn(VpnProfile profile, KeyStore keyStore, LinkProperties egress) {
1099        enforceControlPermission();
1100        long token = Binder.clearCallingIdentity();
1101        try {
1102            startLegacyVpnPrivileged(profile, keyStore, egress);
1103        } finally {
1104            Binder.restoreCallingIdentity(token);
1105        }
1106    }
1107
1108    /**
1109     * Like {@link #startLegacyVpn(VpnProfile, KeyStore, LinkProperties)}, but does not check
1110     * permissions under the assumption that the caller is the system.
1111     *
1112     * Callers are responsible for checking permissions if needed.
1113     */
1114    public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore,
1115            LinkProperties egress) {
1116        UserManager mgr = UserManager.get(mContext);
1117        UserInfo user = mgr.getUserInfo(mUserHandle);
1118        if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN,
1119                    new UserHandle(mUserHandle))) {
1120            throw new SecurityException("Restricted users cannot establish VPNs");
1121        }
1122
1123        final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress);
1124        final String gateway = ipv4DefaultRoute.getGateway().getHostAddress();
1125        final String iface = ipv4DefaultRoute.getInterface();
1126
1127        // Load certificates.
1128        String privateKey = "";
1129        String userCert = "";
1130        String caCert = "";
1131        String serverCert = "";
1132        if (!profile.ipsecUserCert.isEmpty()) {
1133            privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
1134            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert);
1135            userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1136        }
1137        if (!profile.ipsecCaCert.isEmpty()) {
1138            byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert);
1139            caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1140        }
1141        if (!profile.ipsecServerCert.isEmpty()) {
1142            byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert);
1143            serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8);
1144        }
1145        if (privateKey == null || userCert == null || caCert == null || serverCert == null) {
1146            throw new IllegalStateException("Cannot load credentials");
1147        }
1148
1149        // Prepare arguments for racoon.
1150        String[] racoon = null;
1151        switch (profile.type) {
1152            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1153                racoon = new String[] {
1154                    iface, profile.server, "udppsk", profile.ipsecIdentifier,
1155                    profile.ipsecSecret, "1701",
1156                };
1157                break;
1158            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1159                racoon = new String[] {
1160                    iface, profile.server, "udprsa", privateKey, userCert,
1161                    caCert, serverCert, "1701",
1162                };
1163                break;
1164            case VpnProfile.TYPE_IPSEC_XAUTH_PSK:
1165                racoon = new String[] {
1166                    iface, profile.server, "xauthpsk", profile.ipsecIdentifier,
1167                    profile.ipsecSecret, profile.username, profile.password, "", gateway,
1168                };
1169                break;
1170            case VpnProfile.TYPE_IPSEC_XAUTH_RSA:
1171                racoon = new String[] {
1172                    iface, profile.server, "xauthrsa", privateKey, userCert,
1173                    caCert, serverCert, profile.username, profile.password, "", gateway,
1174                };
1175                break;
1176            case VpnProfile.TYPE_IPSEC_HYBRID_RSA:
1177                racoon = new String[] {
1178                    iface, profile.server, "hybridrsa",
1179                    caCert, serverCert, profile.username, profile.password, "", gateway,
1180                };
1181                break;
1182        }
1183
1184        // Prepare arguments for mtpd.
1185        String[] mtpd = null;
1186        switch (profile.type) {
1187            case VpnProfile.TYPE_PPTP:
1188                mtpd = new String[] {
1189                    iface, "pptp", profile.server, "1723",
1190                    "name", profile.username, "password", profile.password,
1191                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1192                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1193                    (profile.mppe ? "+mppe" : "nomppe"),
1194                };
1195                break;
1196            case VpnProfile.TYPE_L2TP_IPSEC_PSK:
1197            case VpnProfile.TYPE_L2TP_IPSEC_RSA:
1198                mtpd = new String[] {
1199                    iface, "l2tp", profile.server, "1701", profile.l2tpSecret,
1200                    "name", profile.username, "password", profile.password,
1201                    "linkname", "vpn", "refuse-eap", "nodefaultroute",
1202                    "usepeerdns", "idle", "1800", "mtu", "1400", "mru", "1400",
1203                };
1204                break;
1205        }
1206
1207        VpnConfig config = new VpnConfig();
1208        config.legacy = true;
1209        config.user = profile.key;
1210        config.interfaze = iface;
1211        config.session = profile.name;
1212
1213        config.addLegacyRoutes(profile.routes);
1214        if (!profile.dnsServers.isEmpty()) {
1215            config.dnsServers = Arrays.asList(profile.dnsServers.split(" +"));
1216        }
1217        if (!profile.searchDomains.isEmpty()) {
1218            config.searchDomains = Arrays.asList(profile.searchDomains.split(" +"));
1219        }
1220        startLegacyVpn(config, racoon, mtpd);
1221    }
1222
1223    private synchronized void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
1224        stopLegacyVpnPrivileged();
1225
1226        // Prepare for the new request.
1227        prepareInternal(VpnConfig.LEGACY_VPN);
1228        updateState(DetailedState.CONNECTING, "startLegacyVpn");
1229
1230        // Start a new LegacyVpnRunner and we are done!
1231        mLegacyVpnRunner = new LegacyVpnRunner(config, racoon, mtpd);
1232        mLegacyVpnRunner.start();
1233    }
1234
1235    /** Stop legacy VPN. Permissions must be checked by callers. */
1236    public synchronized void stopLegacyVpnPrivileged() {
1237        if (mLegacyVpnRunner != null) {
1238            mLegacyVpnRunner.exit();
1239            mLegacyVpnRunner = null;
1240
1241            synchronized (LegacyVpnRunner.TAG) {
1242                // wait for old thread to completely finish before spinning up
1243                // new instance, otherwise state updates can be out of order.
1244            }
1245        }
1246    }
1247
1248    /**
1249     * Return the information of the current ongoing legacy VPN.
1250     */
1251    public synchronized LegacyVpnInfo getLegacyVpnInfo() {
1252        // Check if the caller is authorized.
1253        enforceControlPermission();
1254        return getLegacyVpnInfoPrivileged();
1255    }
1256
1257    /**
1258     * Return the information of the current ongoing legacy VPN.
1259     * Callers are responsible for checking permissions if needed.
1260     */
1261    public synchronized LegacyVpnInfo getLegacyVpnInfoPrivileged() {
1262        if (mLegacyVpnRunner == null) return null;
1263
1264        final LegacyVpnInfo info = new LegacyVpnInfo();
1265        info.key = mConfig.user;
1266        info.state = LegacyVpnInfo.stateFromNetworkInfo(mNetworkInfo);
1267        if (mNetworkInfo.isConnected()) {
1268            info.intent = mStatusIntent;
1269        }
1270        return info;
1271    }
1272
1273    public VpnConfig getLegacyVpnConfig() {
1274        if (mLegacyVpnRunner != null) {
1275            return mConfig;
1276        } else {
1277            return null;
1278        }
1279    }
1280
1281    /**
1282     * Bringing up a VPN connection takes time, and that is all this thread
1283     * does. Here we have plenty of time. The only thing we need to take
1284     * care of is responding to interruptions as soon as possible. Otherwise
1285     * requests will be piled up. This can be done in a Handler as a state
1286     * machine, but it is much easier to read in the current form.
1287     */
1288    private class LegacyVpnRunner extends Thread {
1289        private static final String TAG = "LegacyVpnRunner";
1290
1291        private final String[] mDaemons;
1292        private final String[][] mArguments;
1293        private final LocalSocket[] mSockets;
1294        private final String mOuterInterface;
1295        private final AtomicInteger mOuterConnection =
1296                new AtomicInteger(ConnectivityManager.TYPE_NONE);
1297
1298        private long mTimer = -1;
1299
1300        /**
1301         * Watch for the outer connection (passing in the constructor) going away.
1302         */
1303        private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1304            @Override
1305            public void onReceive(Context context, Intent intent) {
1306                if (!mEnableTeardown) return;
1307
1308                if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1309                    if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1310                            ConnectivityManager.TYPE_NONE) == mOuterConnection.get()) {
1311                        NetworkInfo info = (NetworkInfo)intent.getExtra(
1312                                ConnectivityManager.EXTRA_NETWORK_INFO);
1313                        if (info != null && !info.isConnectedOrConnecting()) {
1314                            try {
1315                                mObserver.interfaceStatusChanged(mOuterInterface, false);
1316                            } catch (RemoteException e) {}
1317                        }
1318                    }
1319                }
1320            }
1321        };
1322
1323        public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
1324            super(TAG);
1325            mConfig = config;
1326            mDaemons = new String[] {"racoon", "mtpd"};
1327            // TODO: clear arguments from memory once launched
1328            mArguments = new String[][] {racoon, mtpd};
1329            mSockets = new LocalSocket[mDaemons.length];
1330
1331            // This is the interface which VPN is running on,
1332            // mConfig.interfaze will change to point to OUR
1333            // internal interface soon. TODO - add inner/outer to mconfig
1334            // TODO - we have a race - if the outer iface goes away/disconnects before we hit this
1335            // we will leave the VPN up.  We should check that it's still there/connected after
1336            // registering
1337            mOuterInterface = mConfig.interfaze;
1338
1339            if (!TextUtils.isEmpty(mOuterInterface)) {
1340                final ConnectivityManager cm = ConnectivityManager.from(mContext);
1341                for (Network network : cm.getAllNetworks()) {
1342                    final LinkProperties lp = cm.getLinkProperties(network);
1343                    if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
1344                        final NetworkInfo networkInfo = cm.getNetworkInfo(network);
1345                        if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
1346                    }
1347                }
1348            }
1349
1350            IntentFilter filter = new IntentFilter();
1351            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1352            mContext.registerReceiver(mBroadcastReceiver, filter);
1353        }
1354
1355        public void check(String interfaze) {
1356            if (interfaze.equals(mOuterInterface)) {
1357                Log.i(TAG, "Legacy VPN is going down with " + interfaze);
1358                exit();
1359            }
1360        }
1361
1362        public void exit() {
1363            // We assume that everything is reset after stopping the daemons.
1364            interrupt();
1365            for (LocalSocket socket : mSockets) {
1366                IoUtils.closeQuietly(socket);
1367            }
1368            agentDisconnect();
1369            try {
1370                mContext.unregisterReceiver(mBroadcastReceiver);
1371            } catch (IllegalArgumentException e) {}
1372        }
1373
1374        @Override
1375        public void run() {
1376            // Wait for the previous thread since it has been interrupted.
1377            Log.v(TAG, "Waiting");
1378            synchronized (TAG) {
1379                Log.v(TAG, "Executing");
1380                execute();
1381                monitorDaemons();
1382            }
1383        }
1384
1385        private void checkpoint(boolean yield) throws InterruptedException {
1386            long now = SystemClock.elapsedRealtime();
1387            if (mTimer == -1) {
1388                mTimer = now;
1389                Thread.sleep(1);
1390            } else if (now - mTimer <= 60000) {
1391                Thread.sleep(yield ? 200 : 1);
1392            } else {
1393                updateState(DetailedState.FAILED, "checkpoint");
1394                throw new IllegalStateException("Time is up");
1395            }
1396        }
1397
1398        private void execute() {
1399            // Catch all exceptions so we can clean up few things.
1400            boolean initFinished = false;
1401            try {
1402                // Initialize the timer.
1403                checkpoint(false);
1404
1405                // Wait for the daemons to stop.
1406                for (String daemon : mDaemons) {
1407                    while (!SystemService.isStopped(daemon)) {
1408                        checkpoint(true);
1409                    }
1410                }
1411
1412                // Clear the previous state.
1413                File state = new File("/data/misc/vpn/state");
1414                state.delete();
1415                if (state.exists()) {
1416                    throw new IllegalStateException("Cannot delete the state");
1417                }
1418                new File("/data/misc/vpn/abort").delete();
1419                initFinished = true;
1420
1421                // Check if we need to restart any of the daemons.
1422                boolean restart = false;
1423                for (String[] arguments : mArguments) {
1424                    restart = restart || (arguments != null);
1425                }
1426                if (!restart) {
1427                    agentDisconnect();
1428                    return;
1429                }
1430                updateState(DetailedState.CONNECTING, "execute");
1431
1432                // Start the daemon with arguments.
1433                for (int i = 0; i < mDaemons.length; ++i) {
1434                    String[] arguments = mArguments[i];
1435                    if (arguments == null) {
1436                        continue;
1437                    }
1438
1439                    // Start the daemon.
1440                    String daemon = mDaemons[i];
1441                    SystemService.start(daemon);
1442
1443                    // Wait for the daemon to start.
1444                    while (!SystemService.isRunning(daemon)) {
1445                        checkpoint(true);
1446                    }
1447
1448                    // Create the control socket.
1449                    mSockets[i] = new LocalSocket();
1450                    LocalSocketAddress address = new LocalSocketAddress(
1451                            daemon, LocalSocketAddress.Namespace.RESERVED);
1452
1453                    // Wait for the socket to connect.
1454                    while (true) {
1455                        try {
1456                            mSockets[i].connect(address);
1457                            break;
1458                        } catch (Exception e) {
1459                            // ignore
1460                        }
1461                        checkpoint(true);
1462                    }
1463                    mSockets[i].setSoTimeout(500);
1464
1465                    // Send over the arguments.
1466                    OutputStream out = mSockets[i].getOutputStream();
1467                    for (String argument : arguments) {
1468                        byte[] bytes = argument.getBytes(StandardCharsets.UTF_8);
1469                        if (bytes.length >= 0xFFFF) {
1470                            throw new IllegalArgumentException("Argument is too large");
1471                        }
1472                        out.write(bytes.length >> 8);
1473                        out.write(bytes.length);
1474                        out.write(bytes);
1475                        checkpoint(false);
1476                    }
1477                    out.write(0xFF);
1478                    out.write(0xFF);
1479                    out.flush();
1480
1481                    // Wait for End-of-File.
1482                    InputStream in = mSockets[i].getInputStream();
1483                    while (true) {
1484                        try {
1485                            if (in.read() == -1) {
1486                                break;
1487                            }
1488                        } catch (Exception e) {
1489                            // ignore
1490                        }
1491                        checkpoint(true);
1492                    }
1493                }
1494
1495                // Wait for the daemons to create the new state.
1496                while (!state.exists()) {
1497                    // Check if a running daemon is dead.
1498                    for (int i = 0; i < mDaemons.length; ++i) {
1499                        String daemon = mDaemons[i];
1500                        if (mArguments[i] != null && !SystemService.isRunning(daemon)) {
1501                            throw new IllegalStateException(daemon + " is dead");
1502                        }
1503                    }
1504                    checkpoint(true);
1505                }
1506
1507                // Now we are connected. Read and parse the new state.
1508                String[] parameters = FileUtils.readTextFile(state, 0, null).split("\n", -1);
1509                if (parameters.length != 7) {
1510                    throw new IllegalStateException("Cannot parse the state");
1511                }
1512
1513                // Set the interface and the addresses in the config.
1514                mConfig.interfaze = parameters[0].trim();
1515
1516                mConfig.addLegacyAddresses(parameters[1]);
1517                // Set the routes if they are not set in the config.
1518                if (mConfig.routes == null || mConfig.routes.isEmpty()) {
1519                    mConfig.addLegacyRoutes(parameters[2]);
1520                }
1521
1522                // Set the DNS servers if they are not set in the config.
1523                if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
1524                    String dnsServers = parameters[3].trim();
1525                    if (!dnsServers.isEmpty()) {
1526                        mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
1527                    }
1528                }
1529
1530                // Set the search domains if they are not set in the config.
1531                if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
1532                    String searchDomains = parameters[4].trim();
1533                    if (!searchDomains.isEmpty()) {
1534                        mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
1535                    }
1536                }
1537
1538                // Add a throw route for the VPN server endpoint, if one was specified.
1539                String endpoint = parameters[5];
1540                if (!endpoint.isEmpty()) {
1541                    try {
1542                        InetAddress addr = InetAddress.parseNumericAddress(endpoint);
1543                        if (addr instanceof Inet4Address) {
1544                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 32), RTN_THROW));
1545                        } else if (addr instanceof Inet6Address) {
1546                            mConfig.routes.add(new RouteInfo(new IpPrefix(addr, 128), RTN_THROW));
1547                        } else {
1548                            Log.e(TAG, "Unknown IP address family for VPN endpoint: " + endpoint);
1549                        }
1550                    } catch (IllegalArgumentException e) {
1551                        Log.e(TAG, "Exception constructing throw route to " + endpoint + ": " + e);
1552                    }
1553                }
1554
1555                // Here is the last step and it must be done synchronously.
1556                synchronized (Vpn.this) {
1557                    // Set the start time
1558                    mConfig.startTime = SystemClock.elapsedRealtime();
1559
1560                    // Check if the thread is interrupted while we are waiting.
1561                    checkpoint(false);
1562
1563                    // Check if the interface is gone while we are waiting.
1564                    if (jniCheck(mConfig.interfaze) == 0) {
1565                        throw new IllegalStateException(mConfig.interfaze + " is gone");
1566                    }
1567
1568                    // Now INetworkManagementEventObserver is watching our back.
1569                    mInterface = mConfig.interfaze;
1570                    prepareStatusIntent();
1571
1572                    agentConnect();
1573
1574                    Log.i(TAG, "Connected!");
1575                }
1576            } catch (Exception e) {
1577                Log.i(TAG, "Aborting", e);
1578                updateState(DetailedState.FAILED, e.getMessage());
1579                exit();
1580            } finally {
1581                // Kill the daemons if they fail to stop.
1582                if (!initFinished) {
1583                    for (String daemon : mDaemons) {
1584                        SystemService.stop(daemon);
1585                    }
1586                }
1587
1588                // Do not leave an unstable state.
1589                if (!initFinished || mNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
1590                    agentDisconnect();
1591                }
1592            }
1593        }
1594
1595        /**
1596         * Monitor the daemons we started, moving to disconnected state if the
1597         * underlying services fail.
1598         */
1599        private void monitorDaemons() {
1600            if (!mNetworkInfo.isConnected()) {
1601                return;
1602            }
1603
1604            try {
1605                while (true) {
1606                    Thread.sleep(2000);
1607                    for (int i = 0; i < mDaemons.length; i++) {
1608                        if (mArguments[i] != null && SystemService.isStopped(mDaemons[i])) {
1609                            return;
1610                        }
1611                    }
1612                }
1613            } catch (InterruptedException e) {
1614                Log.d(TAG, "interrupted during monitorDaemons(); stopping services");
1615            } finally {
1616                for (String daemon : mDaemons) {
1617                    SystemService.stop(daemon);
1618                }
1619
1620                agentDisconnect();
1621            }
1622        }
1623    }
1624}
1625