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