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