]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * Copyright (C) 2012-2018 Tobias Brunner | |
3 | * Copyright (C) 2012 Giuliano Grassi | |
4 | * Copyright (C) 2012 Ralf Sager | |
5 | * | |
6 | * Copyright (C) secunet Security Networks AG | |
7 | * | |
8 | * This program is free software; you can redistribute it and/or modify it | |
9 | * under the terms of the GNU General Public License as published by the | |
10 | * Free Software Foundation; either version 2 of the License, or (at your | |
11 | * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. | |
12 | * | |
13 | * This program is distributed in the hope that it will be useful, but | |
14 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | |
15 | * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
16 | * for more details. | |
17 | */ | |
18 | ||
19 | package org.strongswan.android.logic; | |
20 | ||
21 | import android.annotation.TargetApi; | |
22 | import android.app.Notification; | |
23 | import android.app.NotificationChannel; | |
24 | import android.app.NotificationManager; | |
25 | import android.app.PendingIntent; | |
26 | import android.app.Service; | |
27 | import android.content.ComponentName; | |
28 | import android.content.Context; | |
29 | import android.content.Intent; | |
30 | import android.content.ServiceConnection; | |
31 | import android.content.SharedPreferences; | |
32 | import android.content.pm.PackageManager; | |
33 | import android.net.VpnService; | |
34 | import android.os.Build; | |
35 | import android.os.Bundle; | |
36 | import android.os.Handler; | |
37 | import android.os.IBinder; | |
38 | import android.os.ParcelFileDescriptor; | |
39 | import android.security.KeyChain; | |
40 | import android.security.KeyChainException; | |
41 | import android.system.OsConstants; | |
42 | import android.util.Log; | |
43 | ||
44 | import org.strongswan.android.R; | |
45 | import org.strongswan.android.data.VpnProfile; | |
46 | import org.strongswan.android.data.VpnProfile.SelectedAppsHandling; | |
47 | import org.strongswan.android.data.VpnProfileDataSource; | |
48 | import org.strongswan.android.data.VpnProfileSource; | |
49 | import org.strongswan.android.data.VpnType.VpnTypeFeature; | |
50 | import org.strongswan.android.logic.VpnStateService.ErrorState; | |
51 | import org.strongswan.android.logic.VpnStateService.State; | |
52 | import org.strongswan.android.logic.imc.ImcState; | |
53 | import org.strongswan.android.logic.imc.RemediationInstruction; | |
54 | import org.strongswan.android.ui.MainActivity; | |
55 | import org.strongswan.android.ui.VpnProfileControlActivity; | |
56 | import org.strongswan.android.utils.Constants; | |
57 | import org.strongswan.android.utils.IPRange; | |
58 | import org.strongswan.android.utils.IPRangeSet; | |
59 | import org.strongswan.android.utils.SettingsWriter; | |
60 | import org.strongswan.android.utils.Utils; | |
61 | ||
62 | import java.io.File; | |
63 | import java.io.FileInputStream; | |
64 | import java.io.IOException; | |
65 | import java.net.Inet4Address; | |
66 | import java.net.Inet6Address; | |
67 | import java.net.InetAddress; | |
68 | import java.net.UnknownHostException; | |
69 | import java.nio.ByteBuffer; | |
70 | import java.nio.channels.ClosedByInterruptException; | |
71 | import java.security.PrivateKey; | |
72 | import java.security.cert.CertificateEncodingException; | |
73 | import java.security.cert.X509Certificate; | |
74 | import java.util.ArrayList; | |
75 | import java.util.List; | |
76 | import java.util.Locale; | |
77 | import java.util.SortedSet; | |
78 | ||
79 | import androidx.core.app.NotificationCompat; | |
80 | import androidx.core.content.ContextCompat; | |
81 | import androidx.preference.PreferenceManager; | |
82 | ||
83 | public class CharonVpnService extends VpnService implements Runnable, VpnStateService.VpnStateListener | |
84 | { | |
85 | private static final String TAG = CharonVpnService.class.getSimpleName(); | |
86 | private static final String VPN_SERVICE_ACTION = "android.net.VpnService"; | |
87 | public static final String DISCONNECT_ACTION = "org.strongswan.android.CharonVpnService.DISCONNECT"; | |
88 | private static final String NOTIFICATION_CHANNEL = "org.strongswan.android.CharonVpnService.VPN_STATE_NOTIFICATION"; | |
89 | public static final String LOG_FILE = "charon.log"; | |
90 | public static final String KEY_IS_RETRY = "retry"; | |
91 | public static final int VPN_STATE_NOTIFICATION_ID = 1; | |
92 | ||
93 | private String mLogFile; | |
94 | private String mAppDir; | |
95 | private VpnProfileDataSource mDataSource; | |
96 | private Thread mConnectionHandler; | |
97 | private VpnProfile mCurrentProfile; | |
98 | private volatile String mCurrentCertificateAlias; | |
99 | private volatile String mCurrentUserCertificateAlias; | |
100 | private VpnProfile mNextProfile; | |
101 | private volatile boolean mProfileUpdated; | |
102 | private volatile boolean mTerminate; | |
103 | private volatile boolean mIsDisconnecting; | |
104 | private volatile boolean mShowNotification; | |
105 | private final BuilderAdapter mBuilderAdapter = new BuilderAdapter(); | |
106 | private Handler mHandler; | |
107 | private VpnStateService mService; | |
108 | private final Object mServiceLock = new Object(); | |
109 | private final ServiceConnection mServiceConnection = new ServiceConnection() | |
110 | { | |
111 | @Override | |
112 | public void onServiceDisconnected(ComponentName name) | |
113 | { /* since the service is local this is theoretically only called when the process is terminated */ | |
114 | synchronized (mServiceLock) | |
115 | { | |
116 | mService = null; | |
117 | } | |
118 | } | |
119 | ||
120 | @Override | |
121 | public void onServiceConnected(ComponentName name, IBinder service) | |
122 | { | |
123 | synchronized (mServiceLock) | |
124 | { | |
125 | mService = ((VpnStateService.LocalBinder)service).getService(); | |
126 | } | |
127 | /* we are now ready to start the handler thread */ | |
128 | mService.registerListener(CharonVpnService.this); | |
129 | mConnectionHandler.start(); | |
130 | } | |
131 | }; | |
132 | ||
133 | /** | |
134 | * as defined in charonservice.h | |
135 | */ | |
136 | static final int STATE_CHILD_SA_UP = 1; | |
137 | static final int STATE_CHILD_SA_DOWN = 2; | |
138 | static final int STATE_AUTH_ERROR = 3; | |
139 | static final int STATE_PEER_AUTH_ERROR = 4; | |
140 | static final int STATE_LOOKUP_ERROR = 5; | |
141 | static final int STATE_UNREACHABLE_ERROR = 6; | |
142 | static final int STATE_CERTIFICATE_UNAVAILABLE = 7; | |
143 | static final int STATE_GENERIC_ERROR = 8; | |
144 | ||
145 | @Override | |
146 | public int onStartCommand(Intent intent, int flags, int startId) | |
147 | { | |
148 | if (intent != null) | |
149 | { | |
150 | VpnProfile profile = null; | |
151 | boolean retry = false; | |
152 | ||
153 | if (VPN_SERVICE_ACTION.equals(intent.getAction())) | |
154 | { /* triggered when Always-on VPN is activated */ | |
155 | SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); | |
156 | String uuid = pref.getString(Constants.PREF_DEFAULT_VPN_PROFILE, null); | |
157 | if (uuid == null || uuid.equals(Constants.PREF_DEFAULT_VPN_PROFILE_MRU)) | |
158 | { | |
159 | uuid = pref.getString(Constants.PREF_MRU_VPN_PROFILE, null); | |
160 | } | |
161 | profile = mDataSource.getVpnProfile(uuid); | |
162 | } | |
163 | else if (!DISCONNECT_ACTION.equals(intent.getAction())) | |
164 | { | |
165 | Bundle bundle = intent.getExtras(); | |
166 | if (bundle != null) | |
167 | { | |
168 | profile = mDataSource.getVpnProfile(bundle.getString(VpnProfileDataSource.KEY_UUID)); | |
169 | if (profile != null) | |
170 | { | |
171 | String password = bundle.getString(VpnProfileDataSource.KEY_PASSWORD); | |
172 | profile.setPassword(password); | |
173 | ||
174 | retry = bundle.getBoolean(CharonVpnService.KEY_IS_RETRY, false); | |
175 | ||
176 | SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); | |
177 | pref.edit().putString(Constants.PREF_MRU_VPN_PROFILE, profile.getUUID().toString()) | |
178 | .apply(); | |
179 | } | |
180 | } | |
181 | } | |
182 | if (profile != null && !retry) | |
183 | { /* delete the log file if this is not an automatic retry */ | |
184 | deleteFile(LOG_FILE); | |
185 | } | |
186 | setNextProfile(profile); | |
187 | } | |
188 | return START_NOT_STICKY; | |
189 | } | |
190 | ||
191 | @Override | |
192 | public void onCreate() | |
193 | { | |
194 | mLogFile = getFilesDir().getAbsolutePath() + File.separator + LOG_FILE; | |
195 | mAppDir = getFilesDir().getAbsolutePath(); | |
196 | ||
197 | /* handler used to do changes in the main UI thread */ | |
198 | mHandler = new Handler(getMainLooper()); | |
199 | ||
200 | mDataSource = new VpnProfileSource(this); | |
201 | mDataSource.open(); | |
202 | /* use a separate thread as main thread for charon */ | |
203 | mConnectionHandler = new Thread(this); | |
204 | /* the thread is started when the service is bound */ | |
205 | bindService(new Intent(this, VpnStateService.class), | |
206 | mServiceConnection, Service.BIND_AUTO_CREATE); | |
207 | ||
208 | createNotificationChannel(); | |
209 | } | |
210 | ||
211 | @Override | |
212 | public void onRevoke() | |
213 | { /* the system revoked the rights grated with the initial prepare() call. | |
214 | * called when the user clicks disconnect in the system's VPN dialog */ | |
215 | setNextProfile(null); | |
216 | } | |
217 | ||
218 | @Override | |
219 | public void onDestroy() | |
220 | { | |
221 | mTerminate = true; | |
222 | setNextProfile(null); | |
223 | try | |
224 | { | |
225 | mConnectionHandler.join(); | |
226 | } | |
227 | catch (InterruptedException e) | |
228 | { | |
229 | e.printStackTrace(); | |
230 | } | |
231 | if (mService != null) | |
232 | { | |
233 | mService.unregisterListener(this); | |
234 | unbindService(mServiceConnection); | |
235 | } | |
236 | mDataSource.close(); | |
237 | } | |
238 | ||
239 | /** | |
240 | * Set the profile that is to be initiated next. Notify the handler thread. | |
241 | * | |
242 | * @param profile the profile to initiate | |
243 | */ | |
244 | private void setNextProfile(VpnProfile profile) | |
245 | { | |
246 | synchronized (this) | |
247 | { | |
248 | this.mNextProfile = profile; | |
249 | mProfileUpdated = true; | |
250 | notifyAll(); | |
251 | } | |
252 | } | |
253 | ||
254 | @Override | |
255 | public void run() | |
256 | { | |
257 | while (true) | |
258 | { | |
259 | synchronized (this) | |
260 | { | |
261 | try | |
262 | { | |
263 | while (!mProfileUpdated) | |
264 | { | |
265 | wait(); | |
266 | } | |
267 | ||
268 | mProfileUpdated = false; | |
269 | stopCurrentConnection(); | |
270 | if (mNextProfile == null) | |
271 | { | |
272 | setState(State.DISABLED); | |
273 | if (mTerminate) | |
274 | { | |
275 | break; | |
276 | } | |
277 | } | |
278 | else | |
279 | { | |
280 | mCurrentProfile = mNextProfile; | |
281 | mNextProfile = null; | |
282 | ||
283 | /* store this in a separate (volatile) variable to avoid | |
284 | * a possible deadlock during deinitialization */ | |
285 | mCurrentCertificateAlias = mCurrentProfile.getCertificateAlias(); | |
286 | mCurrentUserCertificateAlias = mCurrentProfile.getUserCertificateAlias(); | |
287 | ||
288 | startConnection(mCurrentProfile); | |
289 | mIsDisconnecting = false; | |
290 | ||
291 | SimpleFetcher.enable(); | |
292 | addNotification(); | |
293 | mBuilderAdapter.setProfile(mCurrentProfile); | |
294 | if (initializeCharon(mBuilderAdapter, mLogFile, mAppDir, mCurrentProfile.getVpnType().has(VpnTypeFeature.BYOD), | |
295 | (mCurrentProfile.getFlags() & VpnProfile.FLAGS_IPv6_TRANSPORT) != 0)) | |
296 | { | |
297 | Log.i(TAG, "charon started"); | |
298 | ||
299 | if (mCurrentProfile.getVpnType().has(VpnTypeFeature.USER_PASS) && | |
300 | mCurrentProfile.getPassword() == null) | |
301 | { /* this can happen if Always-on VPN is enabled with an incomplete profile */ | |
302 | setError(ErrorState.PASSWORD_MISSING); | |
303 | continue; | |
304 | } | |
305 | ||
306 | SettingsWriter writer = new SettingsWriter(); | |
307 | writer.setValue("global.language", Locale.getDefault().getLanguage()); | |
308 | writer.setValue("global.mtu", mCurrentProfile.getMTU()); | |
309 | writer.setValue("global.nat_keepalive", mCurrentProfile.getNATKeepAlive()); | |
310 | writer.setValue("global.rsa_pss", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_RSA_PSS) != 0); | |
311 | writer.setValue("global.crl", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_DISABLE_CRL) == 0); | |
312 | writer.setValue("global.ocsp", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_DISABLE_OCSP) == 0); | |
313 | writer.setValue("connection.type", mCurrentProfile.getVpnType().getIdentifier()); | |
314 | writer.setValue("connection.server", mCurrentProfile.getGateway()); | |
315 | writer.setValue("connection.port", mCurrentProfile.getPort()); | |
316 | writer.setValue("connection.username", mCurrentProfile.getUsername()); | |
317 | writer.setValue("connection.password", mCurrentProfile.getPassword()); | |
318 | writer.setValue("connection.local_id", mCurrentProfile.getLocalId()); | |
319 | writer.setValue("connection.remote_id", mCurrentProfile.getRemoteId()); | |
320 | writer.setValue("connection.certreq", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_SUPPRESS_CERT_REQS) == 0); | |
321 | writer.setValue("connection.strict_revocation", (mCurrentProfile.getFlags() & VpnProfile.FLAGS_STRICT_REVOCATION) != 0); | |
322 | writer.setValue("connection.ike_proposal", mCurrentProfile.getIkeProposal()); | |
323 | writer.setValue("connection.esp_proposal", mCurrentProfile.getEspProposal()); | |
324 | initiate(writer.serialize()); | |
325 | } | |
326 | else | |
327 | { | |
328 | Log.e(TAG, "failed to start charon"); | |
329 | setError(ErrorState.GENERIC_ERROR); | |
330 | setState(State.DISABLED); | |
331 | mCurrentProfile = null; | |
332 | } | |
333 | } | |
334 | } | |
335 | catch (InterruptedException ex) | |
336 | { | |
337 | stopCurrentConnection(); | |
338 | setState(State.DISABLED); | |
339 | } | |
340 | } | |
341 | } | |
342 | } | |
343 | ||
344 | /** | |
345 | * Stop any existing connection by deinitializing charon. | |
346 | */ | |
347 | private void stopCurrentConnection() | |
348 | { | |
349 | synchronized (this) | |
350 | { | |
351 | if (mNextProfile != null) | |
352 | { | |
353 | mBuilderAdapter.setProfile(mNextProfile); | |
354 | mBuilderAdapter.establishBlocking(); | |
355 | } | |
356 | ||
357 | if (mCurrentProfile != null) | |
358 | { | |
359 | setState(State.DISCONNECTING); | |
360 | mIsDisconnecting = true; | |
361 | SimpleFetcher.disable(); | |
362 | deinitializeCharon(); | |
363 | Log.i(TAG, "charon stopped"); | |
364 | mCurrentProfile = null; | |
365 | if (mNextProfile == null) | |
366 | { /* only do this if we are not connecting to another profile */ | |
367 | removeNotification(); | |
368 | mBuilderAdapter.closeBlocking(); | |
369 | } | |
370 | } | |
371 | } | |
372 | } | |
373 | ||
374 | /** | |
375 | * Add a permanent notification while we are connected to avoid the service getting killed by | |
376 | * the system when low on memory. | |
377 | */ | |
378 | private void addNotification() | |
379 | { | |
380 | mHandler.post(new Runnable() | |
381 | { | |
382 | @Override | |
383 | public void run() | |
384 | { | |
385 | mShowNotification = true; | |
386 | startForeground(VPN_STATE_NOTIFICATION_ID, buildNotification(false)); | |
387 | } | |
388 | }); | |
389 | } | |
390 | ||
391 | /** | |
392 | * Remove the permanent notification. | |
393 | */ | |
394 | private void removeNotification() | |
395 | { | |
396 | mHandler.post(new Runnable() | |
397 | { | |
398 | @Override | |
399 | public void run() | |
400 | { | |
401 | mShowNotification = false; | |
402 | stopForeground(true); | |
403 | } | |
404 | }); | |
405 | } | |
406 | ||
407 | /** | |
408 | * Create a notification channel for Android 8+ | |
409 | */ | |
410 | private void createNotificationChannel() | |
411 | { | |
412 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) | |
413 | { | |
414 | NotificationChannel channel; | |
415 | channel = new NotificationChannel(NOTIFICATION_CHANNEL, getString(R.string.permanent_notification_name), | |
416 | NotificationManager.IMPORTANCE_LOW); | |
417 | channel.setDescription(getString(R.string.permanent_notification_description)); | |
418 | channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET); | |
419 | channel.setShowBadge(false); | |
420 | NotificationManager notificationManager = getSystemService(NotificationManager.class); | |
421 | notificationManager.createNotificationChannel(channel); | |
422 | } | |
423 | } | |
424 | ||
425 | ||
426 | /** | |
427 | * Build a notification matching the current state | |
428 | */ | |
429 | private Notification buildNotification(boolean publicVersion) | |
430 | { | |
431 | VpnProfile profile = mService.getProfile(); | |
432 | State state = mService.getState(); | |
433 | ErrorState error = mService.getErrorState(); | |
434 | String name = ""; | |
435 | boolean add_action = false; | |
436 | ||
437 | if (profile != null) | |
438 | { | |
439 | name = profile.getName(); | |
440 | } | |
441 | NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL) | |
442 | .setSmallIcon(R.drawable.ic_notification) | |
443 | .setCategory(NotificationCompat.CATEGORY_SERVICE) | |
444 | .setVisibility(publicVersion ? NotificationCompat.VISIBILITY_PUBLIC | |
445 | : NotificationCompat.VISIBILITY_PRIVATE); | |
446 | int s = R.string.state_disabled; | |
447 | if (error != ErrorState.NO_ERROR) | |
448 | { | |
449 | s = mService.getErrorText(); | |
450 | builder.setSmallIcon(R.drawable.ic_notification_warning); | |
451 | builder.setColor(ContextCompat.getColor(this, R.color.error_text)); | |
452 | ||
453 | if (!publicVersion && profile != null) | |
454 | { | |
455 | int retry = mService.getRetryIn(); | |
456 | if (retry > 0) | |
457 | { | |
458 | builder.setContentText(getResources().getQuantityString(R.plurals.retry_in, retry, retry)); | |
459 | builder.setProgress(mService.getRetryTimeout(), retry, false); | |
460 | } | |
461 | ||
462 | Intent intent = new Intent(getApplicationContext(), VpnProfileControlActivity.class); | |
463 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
464 | intent.setAction(VpnProfileControlActivity.START_PROFILE); | |
465 | intent.putExtra(VpnProfileControlActivity.EXTRA_VPN_PROFILE_UUID, profile.getUUID().toString()); | |
466 | int flags = PendingIntent.FLAG_UPDATE_CURRENT; | |
467 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) | |
468 | { | |
469 | flags |= PendingIntent.FLAG_IMMUTABLE; | |
470 | } | |
471 | PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, | |
472 | flags); | |
473 | builder.addAction(R.drawable.ic_notification_connecting, getString(R.string.retry), pending); | |
474 | add_action = true; | |
475 | } | |
476 | } | |
477 | else | |
478 | { | |
479 | builder.setProgress(0, 0, false); | |
480 | ||
481 | switch (state) | |
482 | { | |
483 | case CONNECTING: | |
484 | s = R.string.state_connecting; | |
485 | builder.setSmallIcon(R.drawable.ic_notification_connecting); | |
486 | builder.setColor(ContextCompat.getColor(this, R.color.warning_text)); | |
487 | add_action = true; | |
488 | break; | |
489 | case CONNECTED: | |
490 | s = R.string.state_connected; | |
491 | builder.setColor(ContextCompat.getColor(this, R.color.success_text)); | |
492 | builder.setUsesChronometer(true); | |
493 | add_action = true; | |
494 | break; | |
495 | case DISCONNECTING: | |
496 | s = R.string.state_disconnecting; | |
497 | break; | |
498 | } | |
499 | } | |
500 | builder.setContentTitle(getString(s)); | |
501 | ||
502 | int flags = PendingIntent.FLAG_UPDATE_CURRENT; | |
503 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) | |
504 | { | |
505 | flags |= PendingIntent.FLAG_IMMUTABLE; | |
506 | } | |
507 | if (!publicVersion) | |
508 | { | |
509 | if (add_action) | |
510 | { | |
511 | Intent intent = new Intent(getApplicationContext(), VpnProfileControlActivity.class); | |
512 | intent.setAction(VpnProfileControlActivity.DISCONNECT); | |
513 | PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, | |
514 | flags); | |
515 | builder.addAction(R.drawable.ic_notification_disconnect, getString(R.string.disconnect), pending); | |
516 | } | |
517 | if (error == ErrorState.NO_ERROR) | |
518 | { | |
519 | builder.setContentText(name); | |
520 | } | |
521 | builder.setPublicVersion(buildNotification(true)); | |
522 | } | |
523 | ||
524 | Intent intent = new Intent(getApplicationContext(), MainActivity.class); | |
525 | PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, | |
526 | flags); | |
527 | builder.setContentIntent(pending); | |
528 | return builder.build(); | |
529 | } | |
530 | ||
531 | @Override | |
532 | public void stateChanged() | |
533 | { | |
534 | if (mShowNotification) | |
535 | { | |
536 | NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); | |
537 | manager.notify(VPN_STATE_NOTIFICATION_ID, buildNotification(false)); | |
538 | } | |
539 | } | |
540 | ||
541 | /** | |
542 | * Notify the state service about a new connection attempt. | |
543 | * Called by the handler thread. | |
544 | * | |
545 | * @param profile currently active VPN profile | |
546 | */ | |
547 | private void startConnection(VpnProfile profile) | |
548 | { | |
549 | synchronized (mServiceLock) | |
550 | { | |
551 | if (mService != null) | |
552 | { | |
553 | mService.startConnection(profile); | |
554 | } | |
555 | } | |
556 | } | |
557 | ||
558 | /** | |
559 | * Update the current VPN state on the state service. Called by the handler | |
560 | * thread and any of charon's threads. | |
561 | * | |
562 | * @param state current state | |
563 | */ | |
564 | private void setState(State state) | |
565 | { | |
566 | synchronized (mServiceLock) | |
567 | { | |
568 | if (mService != null) | |
569 | { | |
570 | mService.setState(state); | |
571 | } | |
572 | } | |
573 | } | |
574 | ||
575 | /** | |
576 | * Set an error on the state service. Called by the handler thread and any | |
577 | * of charon's threads. | |
578 | * | |
579 | * @param error error state | |
580 | */ | |
581 | private void setError(ErrorState error) | |
582 | { | |
583 | synchronized (mServiceLock) | |
584 | { | |
585 | if (mService != null) | |
586 | { | |
587 | mService.setError(error); | |
588 | } | |
589 | } | |
590 | } | |
591 | ||
592 | /** | |
593 | * Set the IMC state on the state service. Called by the handler thread and | |
594 | * any of charon's threads. | |
595 | * | |
596 | * @param state IMC state | |
597 | */ | |
598 | private void setImcState(ImcState state) | |
599 | { | |
600 | synchronized (mServiceLock) | |
601 | { | |
602 | if (mService != null) | |
603 | { | |
604 | mService.setImcState(state); | |
605 | } | |
606 | } | |
607 | } | |
608 | ||
609 | /** | |
610 | * Set an error on the state service. Called by the handler thread and any | |
611 | * of charon's threads. | |
612 | * | |
613 | * @param error error state | |
614 | */ | |
615 | private void setErrorDisconnect(ErrorState error) | |
616 | { | |
617 | synchronized (mServiceLock) | |
618 | { | |
619 | if (mService != null) | |
620 | { | |
621 | if (!mIsDisconnecting) | |
622 | { | |
623 | mService.setError(error); | |
624 | } | |
625 | } | |
626 | } | |
627 | } | |
628 | ||
629 | /** | |
630 | * Updates the state of the current connection. | |
631 | * Called via JNI by different threads (but not concurrently). | |
632 | * | |
633 | * @param status new state | |
634 | */ | |
635 | public void updateStatus(int status) | |
636 | { | |
637 | switch (status) | |
638 | { | |
639 | case STATE_CHILD_SA_DOWN: | |
640 | if (!mIsDisconnecting) | |
641 | { | |
642 | setState(State.CONNECTING); | |
643 | } | |
644 | break; | |
645 | case STATE_CHILD_SA_UP: | |
646 | setState(State.CONNECTED); | |
647 | break; | |
648 | case STATE_AUTH_ERROR: | |
649 | setErrorDisconnect(ErrorState.AUTH_FAILED); | |
650 | break; | |
651 | case STATE_PEER_AUTH_ERROR: | |
652 | setErrorDisconnect(ErrorState.PEER_AUTH_FAILED); | |
653 | break; | |
654 | case STATE_LOOKUP_ERROR: | |
655 | setErrorDisconnect(ErrorState.LOOKUP_FAILED); | |
656 | break; | |
657 | case STATE_UNREACHABLE_ERROR: | |
658 | setErrorDisconnect(ErrorState.UNREACHABLE); | |
659 | break; | |
660 | case STATE_CERTIFICATE_UNAVAILABLE: | |
661 | setErrorDisconnect(ErrorState.CERTIFICATE_UNAVAILABLE); | |
662 | break; | |
663 | case STATE_GENERIC_ERROR: | |
664 | setErrorDisconnect(ErrorState.GENERIC_ERROR); | |
665 | break; | |
666 | default: | |
667 | Log.e(TAG, "Unknown status code received"); | |
668 | break; | |
669 | } | |
670 | } | |
671 | ||
672 | /** | |
673 | * Updates the IMC state of the current connection. | |
674 | * Called via JNI by different threads (but not concurrently). | |
675 | * | |
676 | * @param value new state | |
677 | */ | |
678 | public void updateImcState(int value) | |
679 | { | |
680 | ImcState state = ImcState.fromValue(value); | |
681 | if (state != null) | |
682 | { | |
683 | setImcState(state); | |
684 | } | |
685 | } | |
686 | ||
687 | /** | |
688 | * Add a remediation instruction to the VPN state service. | |
689 | * Called via JNI by different threads (but not concurrently). | |
690 | * | |
691 | * @param xml XML text | |
692 | */ | |
693 | public void addRemediationInstruction(String xml) | |
694 | { | |
695 | for (RemediationInstruction instruction : RemediationInstruction.fromXml(xml)) | |
696 | { | |
697 | synchronized (mServiceLock) | |
698 | { | |
699 | if (mService != null) | |
700 | { | |
701 | mService.addRemediationInstruction(instruction); | |
702 | } | |
703 | } | |
704 | } | |
705 | } | |
706 | ||
707 | /** | |
708 | * Function called via JNI to generate a list of DER encoded CA certificates | |
709 | * as byte array. | |
710 | * | |
711 | * @return a list of DER encoded CA certificates | |
712 | */ | |
713 | private byte[][] getTrustedCertificates() | |
714 | { | |
715 | ArrayList<byte[]> certs = new ArrayList<byte[]>(); | |
716 | TrustedCertificateManager certman = TrustedCertificateManager.getInstance().load(); | |
717 | try | |
718 | { | |
719 | String alias = this.mCurrentCertificateAlias; | |
720 | if (alias != null) | |
721 | { | |
722 | X509Certificate cert = certman.getCACertificateFromAlias(alias); | |
723 | if (cert == null) | |
724 | { | |
725 | return null; | |
726 | } | |
727 | certs.add(cert.getEncoded()); | |
728 | } | |
729 | else | |
730 | { | |
731 | for (X509Certificate cert : certman.getAllCACertificates().values()) | |
732 | { | |
733 | certs.add(cert.getEncoded()); | |
734 | } | |
735 | } | |
736 | } | |
737 | catch (CertificateEncodingException e) | |
738 | { | |
739 | e.printStackTrace(); | |
740 | return null; | |
741 | } | |
742 | return certs.toArray(new byte[certs.size()][]); | |
743 | } | |
744 | ||
745 | /** | |
746 | * Function called via JNI to get a list containing the DER encoded certificates | |
747 | * of the user selected certificate chain (beginning with the user certificate). | |
748 | * | |
749 | * Since this method is called from a thread of charon's thread pool we are safe | |
750 | * to call methods on KeyChain directly. | |
751 | * | |
752 | * @return list containing the certificates (first element is the user certificate) | |
753 | * @throws InterruptedException | |
754 | * @throws KeyChainException | |
755 | * @throws CertificateEncodingException | |
756 | */ | |
757 | private byte[][] getUserCertificate() throws KeyChainException, InterruptedException, CertificateEncodingException | |
758 | { | |
759 | ArrayList<byte[]> encodings = new ArrayList<byte[]>(); | |
760 | X509Certificate[] chain = KeyChain.getCertificateChain(getApplicationContext(), mCurrentUserCertificateAlias); | |
761 | if (chain == null || chain.length == 0) | |
762 | { | |
763 | return null; | |
764 | } | |
765 | for (X509Certificate cert : chain) | |
766 | { | |
767 | encodings.add(cert.getEncoded()); | |
768 | } | |
769 | return encodings.toArray(new byte[encodings.size()][]); | |
770 | } | |
771 | ||
772 | /** | |
773 | * Function called via JNI to get the private key the user selected. | |
774 | * | |
775 | * Since this method is called from a thread of charon's thread pool we are safe | |
776 | * to call methods on KeyChain directly. | |
777 | * | |
778 | * @return the private key | |
779 | * @throws InterruptedException | |
780 | * @throws KeyChainException | |
781 | */ | |
782 | private PrivateKey getUserKey() throws KeyChainException, InterruptedException | |
783 | { | |
784 | return KeyChain.getPrivateKey(getApplicationContext(), mCurrentUserCertificateAlias); | |
785 | } | |
786 | ||
787 | /** | |
788 | * Initialization of charon, provided by libandroidbridge.so | |
789 | * | |
790 | * @param builder BuilderAdapter for this connection | |
791 | * @param logfile absolute path to the logfile | |
792 | * @param appdir absolute path to the data directory of the app | |
793 | * @param byod enable BYOD features | |
794 | * @param ipv6 enable IPv6 transport | |
795 | * @return TRUE if initialization was successful | |
796 | */ | |
797 | public native boolean initializeCharon(BuilderAdapter builder, String logfile, String appdir, boolean byod, boolean ipv6); | |
798 | ||
799 | /** | |
800 | * Deinitialize charon, provided by libandroidbridge.so | |
801 | */ | |
802 | public native void deinitializeCharon(); | |
803 | ||
804 | /** | |
805 | * Initiate VPN, provided by libandroidbridge.so | |
806 | */ | |
807 | public native void initiate(String config); | |
808 | ||
809 | /** | |
810 | * Adapter for VpnService.Builder which is used to access it safely via JNI. | |
811 | * There is a corresponding C object to access it from native code. | |
812 | */ | |
813 | public class BuilderAdapter | |
814 | { | |
815 | private VpnProfile mProfile; | |
816 | private VpnService.Builder mBuilder; | |
817 | private BuilderCache mCache; | |
818 | private BuilderCache mEstablishedCache; | |
819 | private final PacketDropper mDropper = new PacketDropper(); | |
820 | ||
821 | public synchronized void setProfile(VpnProfile profile) | |
822 | { | |
823 | mProfile = profile; | |
824 | mBuilder = createBuilder(mProfile.getName()); | |
825 | mCache = new BuilderCache(mProfile); | |
826 | } | |
827 | ||
828 | private VpnService.Builder createBuilder(String name) | |
829 | { | |
830 | VpnService.Builder builder = new CharonVpnService.Builder(); | |
831 | builder.setSession(name); | |
832 | ||
833 | /* even though the option displayed in the system dialog says "Configure" | |
834 | * we just use our main Activity */ | |
835 | Context context = getApplicationContext(); | |
836 | Intent intent = new Intent(context, MainActivity.class); | |
837 | int flags = PendingIntent.FLAG_UPDATE_CURRENT; | |
838 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) | |
839 | { | |
840 | flags |= PendingIntent.FLAG_IMMUTABLE; | |
841 | } | |
842 | PendingIntent pending = PendingIntent.getActivity(context, 0, intent, flags); | |
843 | builder.setConfigureIntent(pending); | |
844 | ||
845 | /* mark all VPN connections as unmetered (default changed for Android 10) */ | |
846 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) | |
847 | { | |
848 | builder.setMetered(false); | |
849 | } | |
850 | return builder; | |
851 | } | |
852 | ||
853 | public synchronized boolean addAddress(String address, int prefixLength) | |
854 | { | |
855 | try | |
856 | { | |
857 | mCache.addAddress(address, prefixLength); | |
858 | } | |
859 | catch (IllegalArgumentException ex) | |
860 | { | |
861 | return false; | |
862 | } | |
863 | return true; | |
864 | } | |
865 | ||
866 | public synchronized boolean addDnsServer(String address) | |
867 | { | |
868 | try | |
869 | { | |
870 | mCache.addDnsServer(address); | |
871 | } | |
872 | catch (IllegalArgumentException ex) | |
873 | { | |
874 | return false; | |
875 | } | |
876 | return true; | |
877 | } | |
878 | ||
879 | public synchronized boolean addRoute(String address, int prefixLength) | |
880 | { | |
881 | try | |
882 | { | |
883 | mCache.addRoute(address, prefixLength); | |
884 | } | |
885 | catch (IllegalArgumentException ex) | |
886 | { | |
887 | return false; | |
888 | } | |
889 | return true; | |
890 | } | |
891 | ||
892 | public synchronized boolean addSearchDomain(String domain) | |
893 | { | |
894 | try | |
895 | { | |
896 | mBuilder.addSearchDomain(domain); | |
897 | } | |
898 | catch (IllegalArgumentException ex) | |
899 | { | |
900 | return false; | |
901 | } | |
902 | return true; | |
903 | } | |
904 | ||
905 | public synchronized boolean setMtu(int mtu) | |
906 | { | |
907 | try | |
908 | { | |
909 | mCache.setMtu(mtu); | |
910 | } | |
911 | catch (IllegalArgumentException ex) | |
912 | { | |
913 | return false; | |
914 | } | |
915 | return true; | |
916 | } | |
917 | ||
918 | private synchronized ParcelFileDescriptor establishIntern() | |
919 | { | |
920 | ParcelFileDescriptor fd; | |
921 | try | |
922 | { | |
923 | mCache.applyData(mBuilder); | |
924 | fd = mBuilder.establish(); | |
925 | if (fd != null) | |
926 | { | |
927 | closeBlocking(); | |
928 | } | |
929 | } | |
930 | catch (Exception ex) | |
931 | { | |
932 | ex.printStackTrace(); | |
933 | return null; | |
934 | } | |
935 | if (fd == null) | |
936 | { | |
937 | return null; | |
938 | } | |
939 | /* now that the TUN device is created we don't need the current | |
940 | * builder anymore, but we might need another when reestablishing */ | |
941 | mBuilder = createBuilder(mProfile.getName()); | |
942 | mEstablishedCache = mCache; | |
943 | mCache = new BuilderCache(mProfile); | |
944 | return fd; | |
945 | } | |
946 | ||
947 | public synchronized int establish() | |
948 | { | |
949 | ParcelFileDescriptor fd = establishIntern(); | |
950 | return fd != null ? fd.detachFd() : -1; | |
951 | } | |
952 | ||
953 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) | |
954 | public synchronized void establishBlocking() | |
955 | { | |
956 | /* just choose some arbitrary values to block all traffic (except for what's configured in the profile) */ | |
957 | mCache.addAddress("172.16.252.1", 32); | |
958 | mCache.addAddress("fd00::fd02:1", 128); | |
959 | mCache.addRoute("0.0.0.0", 0); | |
960 | mCache.addRoute("::", 0); | |
961 | /* set DNS servers to avoid DNS leak later */ | |
962 | mBuilder.addDnsServer("8.8.8.8"); | |
963 | mBuilder.addDnsServer("2001:4860:4860::8888"); | |
964 | /* use blocking mode to simplify packet dropping */ | |
965 | mBuilder.setBlocking(true); | |
966 | ParcelFileDescriptor fd = establishIntern(); | |
967 | if (fd != null) | |
968 | { | |
969 | mDropper.start(fd); | |
970 | } | |
971 | } | |
972 | ||
973 | public synchronized void closeBlocking() | |
974 | { | |
975 | mDropper.stop(); | |
976 | } | |
977 | ||
978 | public synchronized int establishNoDns() | |
979 | { | |
980 | ParcelFileDescriptor fd; | |
981 | ||
982 | if (mEstablishedCache == null) | |
983 | { | |
984 | return -1; | |
985 | } | |
986 | try | |
987 | { | |
988 | Builder builder = createBuilder(mProfile.getName()); | |
989 | mEstablishedCache.applyData(builder); | |
990 | fd = builder.establish(); | |
991 | } | |
992 | catch (Exception ex) | |
993 | { | |
994 | ex.printStackTrace(); | |
995 | return -1; | |
996 | } | |
997 | if (fd == null) | |
998 | { | |
999 | return -1; | |
1000 | } | |
1001 | return fd.detachFd(); | |
1002 | } | |
1003 | ||
1004 | private class PacketDropper implements Runnable | |
1005 | { | |
1006 | private ParcelFileDescriptor mFd; | |
1007 | private Thread mThread; | |
1008 | ||
1009 | public void start(ParcelFileDescriptor fd) | |
1010 | { | |
1011 | mFd = fd; | |
1012 | mThread = new Thread(this); | |
1013 | mThread.start(); | |
1014 | } | |
1015 | ||
1016 | public void stop() | |
1017 | { | |
1018 | if (mFd != null) | |
1019 | { | |
1020 | try | |
1021 | { | |
1022 | mThread.interrupt(); | |
1023 | mThread.join(); | |
1024 | mFd.close(); | |
1025 | } | |
1026 | catch (InterruptedException e) | |
1027 | { | |
1028 | e.printStackTrace(); | |
1029 | } | |
1030 | catch (IOException e) | |
1031 | { | |
1032 | e.printStackTrace(); | |
1033 | } | |
1034 | mFd = null; | |
1035 | } | |
1036 | } | |
1037 | ||
1038 | @Override | |
1039 | public synchronized void run() | |
1040 | { | |
1041 | try (FileInputStream plain = new FileInputStream(mFd.getFileDescriptor())) | |
1042 | { | |
1043 | ByteBuffer packet = ByteBuffer.allocate(mCache.mMtu); | |
1044 | while (true) | |
1045 | { | |
1046 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) | |
1047 | { /* just read and ignore all data, regular read() is not interruptible */ | |
1048 | int len = plain.getChannel().read(packet); | |
1049 | packet.clear(); | |
1050 | if (len < 0) | |
1051 | { | |
1052 | break; | |
1053 | } | |
1054 | } | |
1055 | else | |
1056 | { /* this is rather ugly but on older platforms not even the NIO version of read() is interruptible */ | |
1057 | boolean wait = true; | |
1058 | if (plain.available() > 0) | |
1059 | { | |
1060 | int len = plain.read(packet.array()); | |
1061 | packet.clear(); | |
1062 | if (len < 0 || Thread.interrupted()) | |
1063 | { | |
1064 | break; | |
1065 | } | |
1066 | /* check again right away, there may be another packet */ | |
1067 | wait = false; | |
1068 | } | |
1069 | if (wait) | |
1070 | { | |
1071 | Thread.sleep(250); | |
1072 | } | |
1073 | } | |
1074 | } | |
1075 | } | |
1076 | catch (final ClosedByInterruptException | InterruptedException e) | |
1077 | { | |
1078 | /* regular interruption */ | |
1079 | } | |
1080 | catch (IOException e) | |
1081 | { | |
1082 | e.printStackTrace(); | |
1083 | } | |
1084 | } | |
1085 | } | |
1086 | } | |
1087 | ||
1088 | /** | |
1089 | * Cache non DNS related information so we can recreate the builder without | |
1090 | * that information when reestablishing IKE_SAs | |
1091 | */ | |
1092 | public class BuilderCache | |
1093 | { | |
1094 | private final List<IPRange> mAddresses = new ArrayList<>(); | |
1095 | private final List<IPRange> mRoutesIPv4 = new ArrayList<>(); | |
1096 | private final List<IPRange> mRoutesIPv6 = new ArrayList<>(); | |
1097 | private final IPRangeSet mIncludedSubnetsv4 = new IPRangeSet(); | |
1098 | private final IPRangeSet mIncludedSubnetsv6 = new IPRangeSet(); | |
1099 | private final IPRangeSet mExcludedSubnets; | |
1100 | private final int mSplitTunneling; | |
1101 | private final SelectedAppsHandling mAppHandling; | |
1102 | private final SortedSet<String> mSelectedApps; | |
1103 | private final List<InetAddress> mDnsServers = new ArrayList<>(); | |
1104 | private int mMtu; | |
1105 | private boolean mIPv4Seen, mIPv6Seen, mDnsServersConfigured; | |
1106 | ||
1107 | public BuilderCache(VpnProfile profile) | |
1108 | { | |
1109 | IPRangeSet included = IPRangeSet.fromString(profile.getIncludedSubnets()); | |
1110 | for (IPRange range : included) | |
1111 | { | |
1112 | if (range.getFrom() instanceof Inet4Address) | |
1113 | { | |
1114 | mIncludedSubnetsv4.add(range); | |
1115 | } | |
1116 | else if (range.getFrom() instanceof Inet6Address) | |
1117 | { | |
1118 | mIncludedSubnetsv6.add(range); | |
1119 | } | |
1120 | } | |
1121 | mExcludedSubnets = IPRangeSet.fromString(profile.getExcludedSubnets()); | |
1122 | Integer splitTunneling = profile.getSplitTunneling(); | |
1123 | mSplitTunneling = splitTunneling != null ? splitTunneling : 0; | |
1124 | SelectedAppsHandling appHandling = profile.getSelectedAppsHandling(); | |
1125 | mSelectedApps = profile.getSelectedAppsSet(); | |
1126 | /* exclude our own app, otherwise the fetcher is blocked */ | |
1127 | switch (appHandling) | |
1128 | { | |
1129 | case SELECTED_APPS_DISABLE: | |
1130 | appHandling = SelectedAppsHandling.SELECTED_APPS_EXCLUDE; | |
1131 | mSelectedApps.clear(); | |
1132 | /* fall-through */ | |
1133 | case SELECTED_APPS_EXCLUDE: | |
1134 | mSelectedApps.add(getPackageName()); | |
1135 | break; | |
1136 | case SELECTED_APPS_ONLY: | |
1137 | mSelectedApps.remove(getPackageName()); | |
1138 | break; | |
1139 | } | |
1140 | mAppHandling = appHandling; | |
1141 | ||
1142 | if (profile.getDnsServers() != null) | |
1143 | { | |
1144 | for (String server : profile.getDnsServers().split("\\s+")) | |
1145 | { | |
1146 | try | |
1147 | { | |
1148 | mDnsServers.add(Utils.parseInetAddress(server)); | |
1149 | recordAddressFamily(server); | |
1150 | mDnsServersConfigured = true; | |
1151 | } | |
1152 | catch (UnknownHostException e) | |
1153 | { | |
1154 | e.printStackTrace(); | |
1155 | } | |
1156 | } | |
1157 | } | |
1158 | ||
1159 | /* set a default MTU, will be set by the daemon for regular interfaces */ | |
1160 | Integer mtu = profile.getMTU(); | |
1161 | mMtu = mtu == null ? Constants.MTU_MAX : mtu; | |
1162 | } | |
1163 | ||
1164 | public void addAddress(String address, int prefixLength) | |
1165 | { | |
1166 | try | |
1167 | { | |
1168 | mAddresses.add(new IPRange(address, prefixLength)); | |
1169 | recordAddressFamily(address); | |
1170 | } | |
1171 | catch (UnknownHostException ex) | |
1172 | { | |
1173 | ex.printStackTrace(); | |
1174 | } | |
1175 | } | |
1176 | ||
1177 | public void addDnsServer(String address) | |
1178 | { | |
1179 | /* ignore received DNS servers if any were configured */ | |
1180 | if (mDnsServersConfigured) | |
1181 | { | |
1182 | return; | |
1183 | } | |
1184 | ||
1185 | try | |
1186 | { | |
1187 | mDnsServers.add(Utils.parseInetAddress(address)); | |
1188 | recordAddressFamily(address); | |
1189 | } | |
1190 | catch (UnknownHostException e) | |
1191 | { | |
1192 | e.printStackTrace(); | |
1193 | } | |
1194 | } | |
1195 | ||
1196 | public void addRoute(String address, int prefixLength) | |
1197 | { | |
1198 | try | |
1199 | { | |
1200 | if (isIPv6(address)) | |
1201 | { | |
1202 | mRoutesIPv6.add(new IPRange(address, prefixLength)); | |
1203 | } | |
1204 | else | |
1205 | { | |
1206 | mRoutesIPv4.add(new IPRange(address, prefixLength)); | |
1207 | } | |
1208 | } | |
1209 | catch (UnknownHostException ex) | |
1210 | { | |
1211 | ex.printStackTrace(); | |
1212 | } | |
1213 | } | |
1214 | ||
1215 | public void setMtu(int mtu) | |
1216 | { | |
1217 | mMtu = mtu; | |
1218 | } | |
1219 | ||
1220 | public void recordAddressFamily(String address) | |
1221 | { | |
1222 | try | |
1223 | { | |
1224 | if (isIPv6(address)) | |
1225 | { | |
1226 | mIPv6Seen = true; | |
1227 | } | |
1228 | else | |
1229 | { | |
1230 | mIPv4Seen = true; | |
1231 | } | |
1232 | } | |
1233 | catch (UnknownHostException ex) | |
1234 | { | |
1235 | ex.printStackTrace(); | |
1236 | } | |
1237 | } | |
1238 | ||
1239 | public void applyData(VpnService.Builder builder) | |
1240 | { | |
1241 | for (IPRange address : mAddresses) | |
1242 | { | |
1243 | builder.addAddress(address.getFrom(), address.getPrefix()); | |
1244 | } | |
1245 | for (InetAddress server : mDnsServers) | |
1246 | { | |
1247 | builder.addDnsServer(server); | |
1248 | } | |
1249 | /* add routes depending on whether split tunneling is allowed or not, | |
1250 | * that is, whether we have to handle and block non-VPN traffic */ | |
1251 | if ((mSplitTunneling & VpnProfile.SPLIT_TUNNELING_BLOCK_IPV4) == 0) | |
1252 | { | |
1253 | if (mIPv4Seen) | |
1254 | { /* split tunneling is used depending on the routes and configuration */ | |
1255 | IPRangeSet ranges = new IPRangeSet(); | |
1256 | if (mIncludedSubnetsv4.size() > 0) | |
1257 | { | |
1258 | ranges.add(mIncludedSubnetsv4); | |
1259 | } | |
1260 | else | |
1261 | { | |
1262 | ranges.addAll(mRoutesIPv4); | |
1263 | } | |
1264 | ranges.remove(mExcludedSubnets); | |
1265 | for (IPRange subnet : ranges.subnets()) | |
1266 | { | |
1267 | try | |
1268 | { | |
1269 | builder.addRoute(subnet.getFrom(), subnet.getPrefix()); | |
1270 | } | |
1271 | catch (IllegalArgumentException e) | |
1272 | { /* some Android versions don't seem to like multicast addresses here, | |
1273 | * ignore it for now */ | |
1274 | if (!subnet.getFrom().isMulticastAddress()) | |
1275 | { | |
1276 | throw e; | |
1277 | } | |
1278 | } | |
1279 | } | |
1280 | } | |
1281 | else | |
1282 | { /* allow traffic that would otherwise be blocked to bypass the VPN */ | |
1283 | builder.allowFamily(OsConstants.AF_INET); | |
1284 | } | |
1285 | } | |
1286 | else if (mIPv4Seen) | |
1287 | { /* only needed if we've seen any addresses. otherwise, traffic | |
1288 | * is blocked by default (we also install no routes in that case) */ | |
1289 | builder.addRoute("0.0.0.0", 0); | |
1290 | } | |
1291 | /* same thing for IPv6 */ | |
1292 | if ((mSplitTunneling & VpnProfile.SPLIT_TUNNELING_BLOCK_IPV6) == 0) | |
1293 | { | |
1294 | if (mIPv6Seen) | |
1295 | { | |
1296 | IPRangeSet ranges = new IPRangeSet(); | |
1297 | if (mIncludedSubnetsv6.size() > 0) | |
1298 | { | |
1299 | ranges.add(mIncludedSubnetsv6); | |
1300 | } | |
1301 | else | |
1302 | { | |
1303 | ranges.addAll(mRoutesIPv6); | |
1304 | } | |
1305 | ranges.remove(mExcludedSubnets); | |
1306 | for (IPRange subnet : ranges.subnets()) | |
1307 | { | |
1308 | try | |
1309 | { | |
1310 | builder.addRoute(subnet.getFrom(), subnet.getPrefix()); | |
1311 | } | |
1312 | catch (IllegalArgumentException e) | |
1313 | { | |
1314 | if (!subnet.getFrom().isMulticastAddress()) | |
1315 | { | |
1316 | throw e; | |
1317 | } | |
1318 | } | |
1319 | } | |
1320 | } | |
1321 | else | |
1322 | { | |
1323 | builder.allowFamily(OsConstants.AF_INET6); | |
1324 | } | |
1325 | } | |
1326 | else if (mIPv6Seen) | |
1327 | { | |
1328 | builder.addRoute("::", 0); | |
1329 | } | |
1330 | /* apply selected applications */ | |
1331 | if (mSelectedApps.size() > 0) | |
1332 | { | |
1333 | switch (mAppHandling) | |
1334 | { | |
1335 | case SELECTED_APPS_EXCLUDE: | |
1336 | for (String app : mSelectedApps) | |
1337 | { | |
1338 | try | |
1339 | { | |
1340 | builder.addDisallowedApplication(app); | |
1341 | } | |
1342 | catch (PackageManager.NameNotFoundException e) | |
1343 | { | |
1344 | // possible if not configured via GUI or app was uninstalled | |
1345 | } | |
1346 | } | |
1347 | break; | |
1348 | case SELECTED_APPS_ONLY: | |
1349 | for (String app : mSelectedApps) | |
1350 | { | |
1351 | try | |
1352 | { | |
1353 | builder.addAllowedApplication(app); | |
1354 | } | |
1355 | catch (PackageManager.NameNotFoundException e) | |
1356 | { | |
1357 | // possible if not configured via GUI or app was uninstalled | |
1358 | } | |
1359 | } | |
1360 | break; | |
1361 | default: | |
1362 | break; | |
1363 | } | |
1364 | } | |
1365 | builder.setMtu(mMtu); | |
1366 | } | |
1367 | ||
1368 | private boolean isIPv6(String address) throws UnknownHostException | |
1369 | { | |
1370 | InetAddress addr = Utils.parseInetAddress(address); | |
1371 | if (addr instanceof Inet4Address) | |
1372 | { | |
1373 | return false; | |
1374 | } | |
1375 | return addr instanceof Inet6Address; | |
1376 | } | |
1377 | } | |
1378 | ||
1379 | /** | |
1380 | * Function called via JNI to determine information about the Android version. | |
1381 | */ | |
1382 | private static String getAndroidVersion() | |
1383 | { | |
1384 | String version = "Android " + Build.VERSION.RELEASE + " - " + Build.DISPLAY; | |
1385 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) | |
1386 | { | |
1387 | version += "/" + Build.VERSION.SECURITY_PATCH; | |
1388 | } | |
1389 | return version; | |
1390 | } | |
1391 | ||
1392 | /** | |
1393 | * Function called via JNI to determine information about the device. | |
1394 | */ | |
1395 | private static String getDeviceString() | |
1396 | { | |
1397 | return Build.MODEL + " - " + Build.BRAND + "/" + Build.PRODUCT + "/" + Build.MANUFACTURER; | |
1398 | } | |
1399 | } |