android: Allow disconnecting via MainActivity but display a confirmation dialog
[strongswan.git] / src / frontends / android / app / src / main / java / org / strongswan / android / logic / CharonVpnService.java
1 /*
2 * Copyright (C) 2012-2017 Tobias Brunner
3 * Copyright (C) 2012 Giuliano Grassi
4 * Copyright (C) 2012 Ralf Sager
5 * HSR Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 package org.strongswan.android.logic;
19
20 import android.annotation.TargetApi;
21 import android.app.Notification;
22 import android.app.NotificationManager;
23 import android.app.PendingIntent;
24 import android.app.Service;
25 import android.content.ComponentName;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.ServiceConnection;
29 import android.content.pm.PackageManager;
30 import android.net.VpnService;
31 import android.os.Build;
32 import android.os.Bundle;
33 import android.os.IBinder;
34 import android.os.ParcelFileDescriptor;
35 import android.security.KeyChain;
36 import android.security.KeyChainException;
37 import android.support.v4.app.NotificationCompat;
38 import android.support.v4.content.ContextCompat;
39 import android.system.OsConstants;
40 import android.util.Log;
41
42 import org.strongswan.android.R;
43 import org.strongswan.android.data.VpnProfile;
44 import org.strongswan.android.data.VpnProfile.SelectedAppsHandling;
45 import org.strongswan.android.data.VpnProfileDataSource;
46 import org.strongswan.android.data.VpnType.VpnTypeFeature;
47 import org.strongswan.android.logic.VpnStateService.ErrorState;
48 import org.strongswan.android.logic.VpnStateService.State;
49 import org.strongswan.android.logic.imc.ImcState;
50 import org.strongswan.android.logic.imc.RemediationInstruction;
51 import org.strongswan.android.ui.MainActivity;
52 import org.strongswan.android.utils.IPRange;
53 import org.strongswan.android.utils.IPRangeSet;
54 import org.strongswan.android.utils.SettingsWriter;
55
56 import java.io.File;
57 import java.net.Inet4Address;
58 import java.net.Inet6Address;
59 import java.net.InetAddress;
60 import java.net.UnknownHostException;
61 import java.security.PrivateKey;
62 import java.security.cert.CertificateEncodingException;
63 import java.security.cert.X509Certificate;
64 import java.util.ArrayList;
65 import java.util.List;
66 import java.util.Locale;
67 import java.util.SortedSet;
68
69 public class CharonVpnService extends VpnService implements Runnable, VpnStateService.VpnStateListener
70 {
71 private static final String TAG = CharonVpnService.class.getSimpleName();
72 public static final String DISCONNECT_ACTION = "org.strongswan.android.CharonVpnService.DISCONNECT";
73 public static final String LOG_FILE = "charon.log";
74 public static final int VPN_STATE_NOTIFICATION_ID = 1;
75
76 private String mLogFile;
77 private VpnProfileDataSource mDataSource;
78 private Thread mConnectionHandler;
79 private VpnProfile mCurrentProfile;
80 private volatile String mCurrentCertificateAlias;
81 private volatile String mCurrentUserCertificateAlias;
82 private VpnProfile mNextProfile;
83 private volatile boolean mProfileUpdated;
84 private volatile boolean mTerminate;
85 private volatile boolean mIsDisconnecting;
86 private volatile boolean mShowNotification;
87 private VpnStateService mService;
88 private final Object mServiceLock = new Object();
89 private final ServiceConnection mServiceConnection = new ServiceConnection() {
90 @Override
91 public void onServiceDisconnected(ComponentName name)
92 { /* since the service is local this is theoretically only called when the process is terminated */
93 synchronized (mServiceLock)
94 {
95 mService = null;
96 }
97 }
98
99 @Override
100 public void onServiceConnected(ComponentName name, IBinder service)
101 {
102 synchronized (mServiceLock)
103 {
104 mService = ((VpnStateService.LocalBinder)service).getService();
105 }
106 /* we are now ready to start the handler thread */
107 mService.registerListener(CharonVpnService.this);
108 mConnectionHandler.start();
109 }
110 };
111
112 /**
113 * as defined in charonservice.h
114 */
115 static final int STATE_CHILD_SA_UP = 1;
116 static final int STATE_CHILD_SA_DOWN = 2;
117 static final int STATE_AUTH_ERROR = 3;
118 static final int STATE_PEER_AUTH_ERROR = 4;
119 static final int STATE_LOOKUP_ERROR = 5;
120 static final int STATE_UNREACHABLE_ERROR = 6;
121 static final int STATE_GENERIC_ERROR = 7;
122
123 @Override
124 public int onStartCommand(Intent intent, int flags, int startId)
125 {
126 if (intent != null)
127 {
128 if (DISCONNECT_ACTION.equals(intent.getAction()))
129 {
130 setNextProfile(null);
131 }
132 else
133 {
134 Bundle bundle = intent.getExtras();
135 VpnProfile profile = null;
136 if (bundle != null)
137 {
138 profile = mDataSource.getVpnProfile(bundle.getLong(VpnProfileDataSource.KEY_ID));
139 if (profile != null)
140 {
141 String password = bundle.getString(VpnProfileDataSource.KEY_PASSWORD);
142 profile.setPassword(password);
143 }
144 }
145 setNextProfile(profile);
146 }
147 }
148 return START_NOT_STICKY;
149 }
150
151 @Override
152 public void onCreate()
153 {
154 mLogFile = getFilesDir().getAbsolutePath() + File.separator + LOG_FILE;
155
156 mDataSource = new VpnProfileDataSource(this);
157 mDataSource.open();
158 /* use a separate thread as main thread for charon */
159 mConnectionHandler = new Thread(this);
160 /* the thread is started when the service is bound */
161 bindService(new Intent(this, VpnStateService.class),
162 mServiceConnection, Service.BIND_AUTO_CREATE);
163 }
164
165 @Override
166 public void onRevoke()
167 { /* the system revoked the rights grated with the initial prepare() call.
168 * called when the user clicks disconnect in the system's VPN dialog */
169 setNextProfile(null);
170 }
171
172 @Override
173 public void onDestroy()
174 {
175 mTerminate = true;
176 setNextProfile(null);
177 try
178 {
179 mConnectionHandler.join();
180 }
181 catch (InterruptedException e)
182 {
183 e.printStackTrace();
184 }
185 if (mService != null)
186 {
187 mService.unregisterListener(this);
188 unbindService(mServiceConnection);
189 }
190 mDataSource.close();
191 }
192
193 /**
194 * Set the profile that is to be initiated next. Notify the handler thread.
195 *
196 * @param profile the profile to initiate
197 */
198 private void setNextProfile(VpnProfile profile)
199 {
200 synchronized (this)
201 {
202 this.mNextProfile = profile;
203 mProfileUpdated = true;
204 notifyAll();
205 }
206 }
207
208 @Override
209 public void run()
210 {
211 while (true)
212 {
213 synchronized (this)
214 {
215 try
216 {
217 while (!mProfileUpdated)
218 {
219 wait();
220 }
221
222 mProfileUpdated = false;
223 stopCurrentConnection();
224 if (mNextProfile == null)
225 {
226 setState(State.DISABLED);
227 if (mTerminate)
228 {
229 break;
230 }
231 }
232 else
233 {
234 mCurrentProfile = mNextProfile;
235 mNextProfile = null;
236
237 /* store this in a separate (volatile) variable to avoid
238 * a possible deadlock during deinitialization */
239 mCurrentCertificateAlias = mCurrentProfile.getCertificateAlias();
240 mCurrentUserCertificateAlias = mCurrentProfile.getUserCertificateAlias();
241
242 startConnection(mCurrentProfile);
243 mIsDisconnecting = false;
244
245 addNotification();
246 BuilderAdapter builder = new BuilderAdapter(mCurrentProfile);
247 if (initializeCharon(builder, mLogFile, mCurrentProfile.getVpnType().has(VpnTypeFeature.BYOD)))
248 {
249 Log.i(TAG, "charon started");
250 SettingsWriter writer = new SettingsWriter();
251 writer.setValue("global.language", Locale.getDefault().getLanguage());
252 writer.setValue("global.mtu", mCurrentProfile.getMTU());
253 writer.setValue("global.nat_keepalive", mCurrentProfile.getNATKeepAlive());
254 writer.setValue("connection.type", mCurrentProfile.getVpnType().getIdentifier());
255 writer.setValue("connection.server", mCurrentProfile.getGateway());
256 writer.setValue("connection.port", mCurrentProfile.getPort());
257 writer.setValue("connection.username", mCurrentProfile.getUsername());
258 writer.setValue("connection.password", mCurrentProfile.getPassword());
259 writer.setValue("connection.local_id", mCurrentProfile.getLocalId());
260 writer.setValue("connection.remote_id", mCurrentProfile.getRemoteId());
261 writer.setValue("connection.certreq", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_SUPPRESS_CERT_REQS) == 0);
262 initiate(writer.serialize());
263 }
264 else
265 {
266 Log.e(TAG, "failed to start charon");
267 setError(ErrorState.GENERIC_ERROR);
268 setState(State.DISABLED);
269 mCurrentProfile = null;
270 }
271 }
272 }
273 catch (InterruptedException ex)
274 {
275 stopCurrentConnection();
276 setState(State.DISABLED);
277 }
278 }
279 }
280 }
281
282 /**
283 * Stop any existing connection by deinitializing charon.
284 */
285 private void stopCurrentConnection()
286 {
287 synchronized (this)
288 {
289 if (mCurrentProfile != null)
290 {
291 setState(State.DISCONNECTING);
292 mIsDisconnecting = true;
293 deinitializeCharon();
294 Log.i(TAG, "charon stopped");
295 mCurrentProfile = null;
296 removeNotification();
297 }
298 }
299 }
300
301 /**
302 * Add a permanent notification while we are connected to avoid the service getting killed by
303 * the system when low on memory.
304 */
305 private void addNotification()
306 {
307 mShowNotification = true;
308 startForeground(VPN_STATE_NOTIFICATION_ID, buildNotification(false));
309 }
310
311 /**
312 * Remove the permanent notification.
313 */
314 private void removeNotification()
315 {
316 mShowNotification = false;
317 stopForeground(true);
318 }
319
320 /**
321 * Build a notification matching the current state
322 */
323 private Notification buildNotification(boolean publicVersion)
324 {
325 VpnProfile profile = mService.getProfile();
326 State state = mService.getState();
327 ErrorState error = mService.getErrorState();
328 String name = "";
329
330 if (profile != null)
331 {
332 name = profile.getName();
333 }
334 android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
335 .setSmallIcon(R.drawable.ic_notification)
336 .setCategory(NotificationCompat.CATEGORY_SERVICE)
337 .setVisibility(publicVersion ? NotificationCompat.VISIBILITY_PUBLIC
338 : NotificationCompat.VISIBILITY_PRIVATE);
339 int s = R.string.state_disabled;
340 if (error != ErrorState.NO_ERROR)
341 {
342 s = R.string.state_error;
343 builder.setSmallIcon(R.drawable.ic_notification_warning);
344 builder.setColor(ContextCompat.getColor(this, R.color.error_text));
345 }
346 else
347 {
348 switch (state)
349 {
350 case CONNECTING:
351 s = R.string.state_connecting;
352 builder.setSmallIcon(R.drawable.ic_notification_warning);
353 builder.setColor(ContextCompat.getColor(this, R.color.warning_text));
354 break;
355 case CONNECTED:
356 s = R.string.state_connected;
357 builder.setColor(ContextCompat.getColor(this, R.color.success_text));
358 builder.setUsesChronometer(true);
359 break;
360 case DISCONNECTING:
361 s = R.string.state_disconnecting;
362 break;
363 }
364 }
365 builder.setContentTitle(getString(s));
366 if (!publicVersion)
367 {
368 Intent intent = new Intent(getApplicationContext(), MainActivity.class);
369 intent.setAction(MainActivity.DISCONNECT);
370 PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent,
371 PendingIntent.FLAG_UPDATE_CURRENT);
372 builder.addAction(R.drawable.ic_notification_disconnect, getString(R.string.disconnect), pending);
373 builder.setContentText(name);
374 builder.setPublicVersion(buildNotification(true));
375 }
376
377 Intent intent = new Intent(getApplicationContext(), MainActivity.class);
378 PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent,
379 PendingIntent.FLAG_UPDATE_CURRENT);
380 builder.setContentIntent(pending);
381 return builder.build();
382 }
383
384 @Override
385 public void stateChanged() {
386 if (mShowNotification)
387 {
388 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
389 manager.notify(VPN_STATE_NOTIFICATION_ID, buildNotification(false));
390 }
391 }
392
393 /**
394 * Notify the state service about a new connection attempt.
395 * Called by the handler thread.
396 *
397 * @param profile currently active VPN profile
398 */
399 private void startConnection(VpnProfile profile)
400 {
401 synchronized (mServiceLock)
402 {
403 if (mService != null)
404 {
405 mService.startConnection(profile);
406 }
407 }
408 }
409
410 /**
411 * Update the current VPN state on the state service. Called by the handler
412 * thread and any of charon's threads.
413 *
414 * @param state current state
415 */
416 private void setState(State state)
417 {
418 synchronized (mServiceLock)
419 {
420 if (mService != null)
421 {
422 mService.setState(state);
423 }
424 }
425 }
426
427 /**
428 * Set an error on the state service. Called by the handler thread and any
429 * of charon's threads.
430 *
431 * @param error error state
432 */
433 private void setError(ErrorState error)
434 {
435 synchronized (mServiceLock)
436 {
437 if (mService != null)
438 {
439 mService.setError(error);
440 }
441 }
442 }
443
444 /**
445 * Set the IMC state on the state service. Called by the handler thread and
446 * any of charon's threads.
447 *
448 * @param state IMC state
449 */
450 private void setImcState(ImcState state)
451 {
452 synchronized (mServiceLock)
453 {
454 if (mService != null)
455 {
456 mService.setImcState(state);
457 }
458 }
459 }
460
461 /**
462 * Set an error on the state service. Called by the handler thread and any
463 * of charon's threads.
464 *
465 * @param error error state
466 */
467 private void setErrorDisconnect(ErrorState error)
468 {
469 synchronized (mServiceLock)
470 {
471 if (mService != null)
472 {
473 if (!mIsDisconnecting)
474 {
475 mService.setError(error);
476 }
477 }
478 }
479 }
480
481 /**
482 * Updates the state of the current connection.
483 * Called via JNI by different threads (but not concurrently).
484 *
485 * @param status new state
486 */
487 public void updateStatus(int status)
488 {
489 switch (status)
490 {
491 case STATE_CHILD_SA_DOWN:
492 if (!mIsDisconnecting)
493 {
494 setState(State.CONNECTING);
495 }
496 break;
497 case STATE_CHILD_SA_UP:
498 setState(State.CONNECTED);
499 break;
500 case STATE_AUTH_ERROR:
501 setErrorDisconnect(ErrorState.AUTH_FAILED);
502 break;
503 case STATE_PEER_AUTH_ERROR:
504 setErrorDisconnect(ErrorState.PEER_AUTH_FAILED);
505 break;
506 case STATE_LOOKUP_ERROR:
507 setErrorDisconnect(ErrorState.LOOKUP_FAILED);
508 break;
509 case STATE_UNREACHABLE_ERROR:
510 setErrorDisconnect(ErrorState.UNREACHABLE);
511 break;
512 case STATE_GENERIC_ERROR:
513 setErrorDisconnect(ErrorState.GENERIC_ERROR);
514 break;
515 default:
516 Log.e(TAG, "Unknown status code received");
517 break;
518 }
519 }
520
521 /**
522 * Updates the IMC state of the current connection.
523 * Called via JNI by different threads (but not concurrently).
524 *
525 * @param value new state
526 */
527 public void updateImcState(int value)
528 {
529 ImcState state = ImcState.fromValue(value);
530 if (state != null)
531 {
532 setImcState(state);
533 }
534 }
535
536 /**
537 * Add a remediation instruction to the VPN state service.
538 * Called via JNI by different threads (but not concurrently).
539 *
540 * @param xml XML text
541 */
542 public void addRemediationInstruction(String xml)
543 {
544 for (RemediationInstruction instruction : RemediationInstruction.fromXml(xml))
545 {
546 synchronized (mServiceLock)
547 {
548 if (mService != null)
549 {
550 mService.addRemediationInstruction(instruction);
551 }
552 }
553 }
554 }
555
556 /**
557 * Function called via JNI to generate a list of DER encoded CA certificates
558 * as byte array.
559 *
560 * @return a list of DER encoded CA certificates
561 */
562 private byte[][] getTrustedCertificates()
563 {
564 ArrayList<byte[]> certs = new ArrayList<byte[]>();
565 TrustedCertificateManager certman = TrustedCertificateManager.getInstance().load();
566 try
567 {
568 String alias = this.mCurrentCertificateAlias;
569 if (alias != null)
570 {
571 X509Certificate cert = certman.getCACertificateFromAlias(alias);
572 if (cert == null)
573 {
574 return null;
575 }
576 certs.add(cert.getEncoded());
577 }
578 else
579 {
580 for (X509Certificate cert : certman.getAllCACertificates().values())
581 {
582 certs.add(cert.getEncoded());
583 }
584 }
585 }
586 catch (CertificateEncodingException e)
587 {
588 e.printStackTrace();
589 return null;
590 }
591 return certs.toArray(new byte[certs.size()][]);
592 }
593
594 /**
595 * Function called via JNI to get a list containing the DER encoded certificates
596 * of the user selected certificate chain (beginning with the user certificate).
597 *
598 * Since this method is called from a thread of charon's thread pool we are safe
599 * to call methods on KeyChain directly.
600 *
601 * @return list containing the certificates (first element is the user certificate)
602 * @throws InterruptedException
603 * @throws KeyChainException
604 * @throws CertificateEncodingException
605 */
606 private byte[][] getUserCertificate() throws KeyChainException, InterruptedException, CertificateEncodingException
607 {
608 ArrayList<byte[]> encodings = new ArrayList<byte[]>();
609 X509Certificate[] chain = KeyChain.getCertificateChain(getApplicationContext(), mCurrentUserCertificateAlias);
610 if (chain == null || chain.length == 0)
611 {
612 return null;
613 }
614 for (X509Certificate cert : chain)
615 {
616 encodings.add(cert.getEncoded());
617 }
618 return encodings.toArray(new byte[encodings.size()][]);
619 }
620
621 /**
622 * Function called via JNI to get the private key the user selected.
623 *
624 * Since this method is called from a thread of charon's thread pool we are safe
625 * to call methods on KeyChain directly.
626 *
627 * @return the private key
628 * @throws InterruptedException
629 * @throws KeyChainException
630 * @throws CertificateEncodingException
631 */
632 private PrivateKey getUserKey() throws KeyChainException, InterruptedException
633 {
634 return KeyChain.getPrivateKey(getApplicationContext(), mCurrentUserCertificateAlias);
635 }
636
637 /**
638 * Initialization of charon, provided by libandroidbridge.so
639 *
640 * @param builder BuilderAdapter for this connection
641 * @param logfile absolute path to the logfile
642 * @param byod enable BYOD features
643 * @return TRUE if initialization was successful
644 */
645 public native boolean initializeCharon(BuilderAdapter builder, String logfile, boolean byod);
646
647 /**
648 * Deinitialize charon, provided by libandroidbridge.so
649 */
650 public native void deinitializeCharon();
651
652 /**
653 * Initiate VPN, provided by libandroidbridge.so
654 */
655 public native void initiate(String config);
656
657 /**
658 * Adapter for VpnService.Builder which is used to access it safely via JNI.
659 * There is a corresponding C object to access it from native code.
660 */
661 public class BuilderAdapter
662 {
663 private final VpnProfile mProfile;
664 private VpnService.Builder mBuilder;
665 private BuilderCache mCache;
666 private BuilderCache mEstablishedCache;
667
668 public BuilderAdapter(VpnProfile profile)
669 {
670 mProfile = profile;
671 mBuilder = createBuilder(mProfile.getName());
672 mCache = new BuilderCache(mProfile);
673 }
674
675 private VpnService.Builder createBuilder(String name)
676 {
677 VpnService.Builder builder = new CharonVpnService.Builder();
678 builder.setSession(name);
679
680 /* even though the option displayed in the system dialog says "Configure"
681 * we just use our main Activity */
682 Context context = getApplicationContext();
683 Intent intent = new Intent(context, MainActivity.class);
684 PendingIntent pending = PendingIntent.getActivity(context, 0, intent,
685 PendingIntent.FLAG_UPDATE_CURRENT);
686 builder.setConfigureIntent(pending);
687 return builder;
688 }
689
690 public synchronized boolean addAddress(String address, int prefixLength)
691 {
692 try
693 {
694 mCache.addAddress(address, prefixLength);
695 }
696 catch (IllegalArgumentException ex)
697 {
698 return false;
699 }
700 return true;
701 }
702
703 public synchronized boolean addDnsServer(String address)
704 {
705 try
706 {
707 mBuilder.addDnsServer(address);
708 mCache.recordAddressFamily(address);
709 }
710 catch (IllegalArgumentException ex)
711 {
712 return false;
713 }
714 return true;
715 }
716
717 public synchronized boolean addRoute(String address, int prefixLength)
718 {
719 try
720 {
721 mCache.addRoute(address, prefixLength);
722 }
723 catch (IllegalArgumentException ex)
724 {
725 return false;
726 }
727 return true;
728 }
729
730 public synchronized boolean addSearchDomain(String domain)
731 {
732 try
733 {
734 mBuilder.addSearchDomain(domain);
735 }
736 catch (IllegalArgumentException ex)
737 {
738 return false;
739 }
740 return true;
741 }
742
743 public synchronized boolean setMtu(int mtu)
744 {
745 try
746 {
747 mCache.setMtu(mtu);
748 }
749 catch (IllegalArgumentException ex)
750 {
751 return false;
752 }
753 return true;
754 }
755
756 public synchronized int establish()
757 {
758 ParcelFileDescriptor fd;
759 try
760 {
761 mCache.applyData(mBuilder);
762 fd = mBuilder.establish();
763 }
764 catch (Exception ex)
765 {
766 ex.printStackTrace();
767 return -1;
768 }
769 if (fd == null)
770 {
771 return -1;
772 }
773 /* now that the TUN device is created we don't need the current
774 * builder anymore, but we might need another when reestablishing */
775 mBuilder = createBuilder(mProfile.getName());
776 mEstablishedCache = mCache;
777 mCache = new BuilderCache(mProfile);
778 return fd.detachFd();
779 }
780
781 public synchronized int establishNoDns()
782 {
783 ParcelFileDescriptor fd;
784
785 if (mEstablishedCache == null)
786 {
787 return -1;
788 }
789 try
790 {
791 Builder builder = createBuilder(mProfile.getName());
792 mEstablishedCache.applyData(builder);
793 fd = builder.establish();
794 }
795 catch (Exception ex)
796 {
797 ex.printStackTrace();
798 return -1;
799 }
800 if (fd == null)
801 {
802 return -1;
803 }
804 return fd.detachFd();
805 }
806 }
807
808 /**
809 * Cache non DNS related information so we can recreate the builder without
810 * that information when reestablishing IKE_SAs
811 */
812 public class BuilderCache
813 {
814 private final List<IPRange> mAddresses = new ArrayList<>();
815 private final List<IPRange> mRoutesIPv4 = new ArrayList<>();
816 private final List<IPRange> mRoutesIPv6 = new ArrayList<>();
817 private final IPRangeSet mIncludedSubnetsv4 = new IPRangeSet();
818 private final IPRangeSet mIncludedSubnetsv6 = new IPRangeSet();
819 private final IPRangeSet mExcludedSubnets;
820 private final int mSplitTunneling;
821 private final SelectedAppsHandling mAppHandling;
822 private final SortedSet<String> mSelectedApps;
823 private int mMtu;
824 private boolean mIPv4Seen, mIPv6Seen;
825
826 public BuilderCache(VpnProfile profile)
827 {
828 IPRangeSet included = IPRangeSet.fromString(profile.getIncludedSubnets());
829 for (IPRange range : included)
830 {
831 if (range.getFrom() instanceof Inet4Address)
832 {
833 mIncludedSubnetsv4.add(range);
834 }
835 else if (range.getFrom() instanceof Inet6Address)
836 {
837 mIncludedSubnetsv6.add(range);
838 }
839 }
840 mExcludedSubnets = IPRangeSet.fromString(profile.getExcludedSubnets());
841 Integer splitTunneling = profile.getSplitTunneling();
842 mSplitTunneling = splitTunneling != null ? splitTunneling : 0;
843 mAppHandling = profile.getSelectedAppsHandling();
844 mSelectedApps = profile.getSelectedAppsSet();
845 }
846
847 public void addAddress(String address, int prefixLength)
848 {
849 try
850 {
851 mAddresses.add(new IPRange(address, prefixLength));
852 recordAddressFamily(address);
853 }
854 catch (UnknownHostException ex)
855 {
856 ex.printStackTrace();
857 }
858 }
859
860 public void addRoute(String address, int prefixLength)
861 {
862 try
863 {
864 if (isIPv6(address))
865 {
866 mRoutesIPv6.add(new IPRange(address, prefixLength));
867 }
868 else
869 {
870 mRoutesIPv4.add(new IPRange(address, prefixLength));
871 }
872 }
873 catch (UnknownHostException ex)
874 {
875 ex.printStackTrace();
876 }
877 }
878
879 public void setMtu(int mtu)
880 {
881 mMtu = mtu;
882 }
883
884 public void recordAddressFamily(String address)
885 {
886 try
887 {
888 if (isIPv6(address))
889 {
890 mIPv6Seen = true;
891 }
892 else
893 {
894 mIPv4Seen = true;
895 }
896 }
897 catch (UnknownHostException ex)
898 {
899 ex.printStackTrace();
900 }
901 }
902
903 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
904 public void applyData(VpnService.Builder builder)
905 {
906 for (IPRange address : mAddresses)
907 {
908 builder.addAddress(address.getFrom(), address.getPrefix());
909 }
910 /* add routes depending on whether split tunneling is allowed or not,
911 * that is, whether we have to handle and block non-VPN traffic */
912 if ((mSplitTunneling & VpnProfile.SPLIT_TUNNELING_BLOCK_IPV4) == 0)
913 {
914 if (mIPv4Seen)
915 { /* split tunneling is used depending on the routes and configuration */
916 IPRangeSet ranges = new IPRangeSet();
917 if (mIncludedSubnetsv4.size() > 0)
918 {
919 ranges.add(mIncludedSubnetsv4);
920 }
921 else
922 {
923 ranges.addAll(mRoutesIPv4);
924 }
925 ranges.remove(mExcludedSubnets);
926 for (IPRange subnet : ranges.subnets())
927 {
928 builder.addRoute(subnet.getFrom(), subnet.getPrefix());
929 }
930 }
931 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
932 { /* allow traffic that would otherwise be blocked to bypass the VPN */
933 builder.allowFamily(OsConstants.AF_INET);
934 }
935 }
936 else if (mIPv4Seen)
937 { /* only needed if we've seen any addresses. otherwise, traffic
938 * is blocked by default (we also install no routes in that case) */
939 builder.addRoute("0.0.0.0", 0);
940 }
941 /* same thing for IPv6 */
942 if ((mSplitTunneling & VpnProfile.SPLIT_TUNNELING_BLOCK_IPV6) == 0)
943 {
944 if (mIPv6Seen)
945 {
946 IPRangeSet ranges = new IPRangeSet();
947 if (mIncludedSubnetsv6.size() > 0)
948 {
949 ranges.add(mIncludedSubnetsv6);
950 }
951 else
952 {
953 ranges.addAll(mRoutesIPv6);
954 }
955 ranges.remove(mExcludedSubnets);
956 for (IPRange subnet : ranges.subnets())
957 {
958 builder.addRoute(subnet.getFrom(), subnet.getPrefix());
959 }
960 }
961 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
962 {
963 builder.allowFamily(OsConstants.AF_INET6);
964 }
965 }
966 else if (mIPv6Seen)
967 {
968 builder.addRoute("::", 0);
969 }
970 /* apply selected applications */
971 if (mSelectedApps.size() > 0)
972 {
973 switch (mAppHandling)
974 {
975 case SELECTED_APPS_EXCLUDE:
976 for (String app : mSelectedApps)
977 {
978 try
979 {
980 builder.addDisallowedApplication(app);
981 }
982 catch (PackageManager.NameNotFoundException e)
983 {
984 // possible if not configured via GUI or app was uninstalled
985 }
986 }
987 break;
988 case SELECTED_APPS_ONLY:
989 for (String app : mSelectedApps)
990 {
991 try
992 {
993 builder.addAllowedApplication(app);
994 }
995 catch (PackageManager.NameNotFoundException e)
996 {
997 // possible if not configured via GUI or app was uninstalled
998 }
999 }
1000 break;
1001 default:
1002 break;
1003 }
1004 }
1005 builder.setMtu(mMtu);
1006 }
1007
1008 private boolean isIPv6(String address) throws UnknownHostException
1009 {
1010 InetAddress addr = InetAddress.getByName(address);
1011 if (addr instanceof Inet4Address)
1012 {
1013 return false;
1014 }
1015 else if (addr instanceof Inet6Address)
1016 {
1017 return true;
1018 }
1019 return false;
1020 }
1021 }
1022
1023 /**
1024 * Function called via JNI to determine information about the Android version.
1025 */
1026 private static String getAndroidVersion()
1027 {
1028 return "Android " + Build.VERSION.RELEASE + " - " + Build.DISPLAY +
1029 "/" + Build.VERSION.SECURITY_PATCH;
1030 }
1031
1032 /**
1033 * Function called via JNI to determine information about the device.
1034 */
1035 private static String getDeviceString()
1036 {
1037 return Build.MODEL + " - " + Build.BRAND + "/" + Build.PRODUCT + "/" + Build.MANUFACTURER;
1038 }
1039
1040 /*
1041 * The libraries are extracted to /data/data/org.strongswan.android/...
1042 * during installation. On newer releases most are loaded in JNI_OnLoad.
1043 */
1044 static
1045 {
1046 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
1047 {
1048 System.loadLibrary("strongswan");
1049
1050 if (MainActivity.USE_BYOD)
1051 {
1052 System.loadLibrary("tpmtss");
1053 System.loadLibrary("tncif");
1054 System.loadLibrary("tnccs");
1055 System.loadLibrary("imcv");
1056 }
1057
1058 System.loadLibrary("charon");
1059 System.loadLibrary("ipsec");
1060 }
1061 System.loadLibrary("androidbridge");
1062 }
1063 }