a7b8a8ceffcec57d14e3ba8ffa6e616932c6e005
[strongswan.git] / src / frontends / android / src / org / strongswan / android / logic / CharonVpnService.java
1 /*
2 * Copyright (C) 2012-2013 Tobias Brunner
3 * Copyright (C) 2012 Giuliano Grassi
4 * Copyright (C) 2012 Ralf Sager
5 * 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 java.io.File;
21 import java.security.PrivateKey;
22 import java.security.cert.CertificateEncodingException;
23 import java.security.cert.X509Certificate;
24 import java.util.ArrayList;
25
26 import org.strongswan.android.data.VpnProfile;
27 import org.strongswan.android.data.VpnProfileDataSource;
28 import org.strongswan.android.logic.VpnStateService.ErrorState;
29 import org.strongswan.android.logic.VpnStateService.State;
30 import org.strongswan.android.logic.imc.ImcState;
31 import org.strongswan.android.logic.imc.RemediationInstruction;
32 import org.strongswan.android.ui.MainActivity;
33
34 import android.app.PendingIntent;
35 import android.app.Service;
36 import android.content.ComponentName;
37 import android.content.Context;
38 import android.content.Intent;
39 import android.content.ServiceConnection;
40 import android.net.VpnService;
41 import android.os.Bundle;
42 import android.os.IBinder;
43 import android.os.ParcelFileDescriptor;
44 import android.security.KeyChain;
45 import android.security.KeyChainException;
46 import android.util.Log;
47
48 public class CharonVpnService extends VpnService implements Runnable
49 {
50 private static final String TAG = CharonVpnService.class.getSimpleName();
51 public static final String LOG_FILE = "charon.log";
52
53 private String mLogFile;
54 private VpnProfileDataSource mDataSource;
55 private Thread mConnectionHandler;
56 private VpnProfile mCurrentProfile;
57 private volatile String mCurrentCertificateAlias;
58 private volatile String mCurrentUserCertificateAlias;
59 private VpnProfile mNextProfile;
60 private volatile boolean mProfileUpdated;
61 private volatile boolean mTerminate;
62 private volatile boolean mIsDisconnecting;
63 private VpnStateService mService;
64 private final Object mServiceLock = new Object();
65 private final ServiceConnection mServiceConnection = new ServiceConnection() {
66 @Override
67 public void onServiceDisconnected(ComponentName name)
68 { /* since the service is local this is theoretically only called when the process is terminated */
69 synchronized (mServiceLock)
70 {
71 mService = null;
72 }
73 }
74
75 @Override
76 public void onServiceConnected(ComponentName name, IBinder service)
77 {
78 synchronized (mServiceLock)
79 {
80 mService = ((VpnStateService.LocalBinder)service).getService();
81 }
82 /* we are now ready to start the handler thread */
83 mConnectionHandler.start();
84 }
85 };
86
87 /**
88 * as defined in charonservice.h
89 */
90 static final int STATE_CHILD_SA_UP = 1;
91 static final int STATE_CHILD_SA_DOWN = 2;
92 static final int STATE_AUTH_ERROR = 3;
93 static final int STATE_PEER_AUTH_ERROR = 4;
94 static final int STATE_LOOKUP_ERROR = 5;
95 static final int STATE_UNREACHABLE_ERROR = 6;
96 static final int STATE_GENERIC_ERROR = 7;
97
98 @Override
99 public int onStartCommand(Intent intent, int flags, int startId)
100 {
101 if (intent != null)
102 {
103 Bundle bundle = intent.getExtras();
104 VpnProfile profile = null;
105 if (bundle != null)
106 {
107 profile = mDataSource.getVpnProfile(bundle.getLong(VpnProfileDataSource.KEY_ID));
108 if (profile != null)
109 {
110 String password = bundle.getString(VpnProfileDataSource.KEY_PASSWORD);
111 profile.setPassword(password);
112 }
113 }
114 setNextProfile(profile);
115 }
116 return START_NOT_STICKY;
117 }
118
119 @Override
120 public void onCreate()
121 {
122 mLogFile = getFilesDir().getAbsolutePath() + File.separator + LOG_FILE;
123
124 mDataSource = new VpnProfileDataSource(this);
125 mDataSource.open();
126 /* use a separate thread as main thread for charon */
127 mConnectionHandler = new Thread(this);
128 /* the thread is started when the service is bound */
129 bindService(new Intent(this, VpnStateService.class),
130 mServiceConnection, Service.BIND_AUTO_CREATE);
131 }
132
133 @Override
134 public void onRevoke()
135 { /* the system revoked the rights grated with the initial prepare() call.
136 * called when the user clicks disconnect in the system's VPN dialog */
137 setNextProfile(null);
138 }
139
140 @Override
141 public void onDestroy()
142 {
143 mTerminate = true;
144 setNextProfile(null);
145 try
146 {
147 mConnectionHandler.join();
148 }
149 catch (InterruptedException e)
150 {
151 e.printStackTrace();
152 }
153 if (mService != null)
154 {
155 unbindService(mServiceConnection);
156 }
157 mDataSource.close();
158 }
159
160 /**
161 * Set the profile that is to be initiated next. Notify the handler thread.
162 *
163 * @param profile the profile to initiate
164 */
165 private void setNextProfile(VpnProfile profile)
166 {
167 synchronized (this)
168 {
169 this.mNextProfile = profile;
170 mProfileUpdated = true;
171 notifyAll();
172 }
173 }
174
175 @Override
176 public void run()
177 {
178 while (true)
179 {
180 synchronized (this)
181 {
182 try
183 {
184 while (!mProfileUpdated)
185 {
186 wait();
187 }
188
189 mProfileUpdated = false;
190 stopCurrentConnection();
191 if (mNextProfile == null)
192 {
193 setProfile(null);
194 setState(State.DISABLED);
195 if (mTerminate)
196 {
197 break;
198 }
199 }
200 else
201 {
202 mCurrentProfile = mNextProfile;
203 mNextProfile = null;
204
205 /* store this in a separate (volatile) variable to avoid
206 * a possible deadlock during deinitialization */
207 mCurrentCertificateAlias = mCurrentProfile.getCertificateAlias();
208 mCurrentUserCertificateAlias = mCurrentProfile.getUserCertificateAlias();
209
210 setProfile(mCurrentProfile);
211 setError(ErrorState.NO_ERROR);
212 setState(State.CONNECTING);
213 setImcState(ImcState.UNKNOWN);
214 mIsDisconnecting = false;
215
216 BuilderAdapter builder = new BuilderAdapter(mCurrentProfile.getName());
217 initializeCharon(builder, mLogFile, mCurrentProfile.getVpnType().getEnableBYOD());
218 Log.i(TAG, "charon started");
219
220 initiate(mCurrentProfile.getVpnType().getIdentifier(),
221 mCurrentProfile.getGateway(), mCurrentProfile.getUsername(),
222 mCurrentProfile.getPassword());
223 }
224 }
225 catch (InterruptedException ex)
226 {
227 stopCurrentConnection();
228 setState(State.DISABLED);
229 }
230 }
231 }
232 }
233
234 /**
235 * Stop any existing connection by deinitializing charon.
236 */
237 private void stopCurrentConnection()
238 {
239 synchronized (this)
240 {
241 if (mCurrentProfile != null)
242 {
243 setState(State.DISCONNECTING);
244 mIsDisconnecting = true;
245 deinitializeCharon();
246 Log.i(TAG, "charon stopped");
247 mCurrentProfile = null;
248 }
249 }
250 }
251
252 /**
253 * Update the VPN profile on the state service. Called by the handler thread.
254 *
255 * @param profile currently active VPN profile
256 */
257 private void setProfile(VpnProfile profile)
258 {
259 synchronized (mServiceLock)
260 {
261 if (mService != null)
262 {
263 mService.setProfile(profile);
264 }
265 }
266 }
267
268 /**
269 * Update the current VPN state on the state service. Called by the handler
270 * thread and any of charon's threads.
271 *
272 * @param state current state
273 */
274 private void setState(State state)
275 {
276 synchronized (mServiceLock)
277 {
278 if (mService != null)
279 {
280 mService.setState(state);
281 }
282 }
283 }
284
285 /**
286 * Set an error on the state service. Called by the handler thread and any
287 * of charon's threads.
288 *
289 * @param error error state
290 */
291 private void setError(ErrorState error)
292 {
293 synchronized (mServiceLock)
294 {
295 if (mService != null)
296 {
297 mService.setError(error);
298 }
299 }
300 }
301
302 /**
303 * Set the IMC state on the state service. Called by the handler thread and
304 * any of charon's threads.
305 *
306 * @param state IMC state
307 */
308 private void setImcState(ImcState state)
309 {
310 synchronized (mServiceLock)
311 {
312 if (mService != null)
313 {
314 mService.setImcState(state);
315 }
316 }
317 }
318
319 /**
320 * Set an error on the state service and disconnect the current connection.
321 * This is not done by calling stopCurrentConnection() above, but instead
322 * is done asynchronously via state service.
323 *
324 * @param error error state
325 */
326 private void setErrorDisconnect(ErrorState error)
327 {
328 synchronized (mServiceLock)
329 {
330 if (mService != null)
331 {
332 mService.setError(error);
333 if (!mIsDisconnecting)
334 {
335 mService.disconnect();
336 }
337 }
338 }
339 }
340
341 /**
342 * Updates the state of the current connection.
343 * Called via JNI by different threads (but not concurrently).
344 *
345 * @param status new state
346 */
347 public void updateStatus(int status)
348 {
349 switch (status)
350 {
351 case STATE_CHILD_SA_DOWN:
352 /* we ignore this as we use closeaction=restart */
353 break;
354 case STATE_CHILD_SA_UP:
355 setState(State.CONNECTED);
356 break;
357 case STATE_AUTH_ERROR:
358 setErrorDisconnect(ErrorState.AUTH_FAILED);
359 break;
360 case STATE_PEER_AUTH_ERROR:
361 setErrorDisconnect(ErrorState.PEER_AUTH_FAILED);
362 break;
363 case STATE_LOOKUP_ERROR:
364 setErrorDisconnect(ErrorState.LOOKUP_FAILED);
365 break;
366 case STATE_UNREACHABLE_ERROR:
367 setErrorDisconnect(ErrorState.UNREACHABLE);
368 break;
369 case STATE_GENERIC_ERROR:
370 setErrorDisconnect(ErrorState.GENERIC_ERROR);
371 break;
372 default:
373 Log.e(TAG, "Unknown status code received");
374 break;
375 }
376 }
377
378 /**
379 * Updates the IMC state of the current connection.
380 * Called via JNI by different threads (but not concurrently).
381 *
382 * @param value new state
383 */
384 public void updateImcState(int value)
385 {
386 ImcState state = ImcState.fromValue(value);
387 if (state != null)
388 {
389 setImcState(state);
390 }
391 }
392
393 /**
394 * Add a remediation instruction to the VPN state service.
395 * Called via JNI by different threads (but not concurrently).
396 *
397 * @param xml XML text
398 */
399 public void addRemediationInstruction(String xml)
400 {
401 for (RemediationInstruction instruction : RemediationInstruction.fromXml(xml))
402 {
403 synchronized (mServiceLock)
404 {
405 if (mService != null)
406 {
407 mService.addRemediationInstruction(instruction);
408 }
409 }
410 }
411 }
412
413 /**
414 * Function called via JNI to generate a list of DER encoded CA certificates
415 * as byte array.
416 *
417 * @param hash optional alias (only hash part), if given matching certificates are returned
418 * @return a list of DER encoded CA certificates
419 */
420 private byte[][] getTrustedCertificates(String hash)
421 {
422 ArrayList<byte[]> certs = new ArrayList<byte[]>();
423 TrustedCertificateManager certman = TrustedCertificateManager.getInstance();
424 try
425 {
426 if (hash != null)
427 {
428 String alias = "user:" + hash + ".0";
429 X509Certificate cert = certman.getCACertificateFromAlias(alias);
430 if (cert == null)
431 {
432 alias = "system:" + hash + ".0";
433 cert = certman.getCACertificateFromAlias(alias);
434 }
435 if (cert == null)
436 {
437 return null;
438 }
439 certs.add(cert.getEncoded());
440 }
441 else
442 {
443 String alias = this.mCurrentCertificateAlias;
444 if (alias != null)
445 {
446 X509Certificate cert = certman.getCACertificateFromAlias(alias);
447 if (cert == null)
448 {
449 return null;
450 }
451 certs.add(cert.getEncoded());
452 }
453 else
454 {
455 for (X509Certificate cert : certman.getAllCACertificates().values())
456 {
457 certs.add(cert.getEncoded());
458 }
459 }
460 }
461 }
462 catch (CertificateEncodingException e)
463 {
464 e.printStackTrace();
465 return null;
466 }
467 return certs.toArray(new byte[certs.size()][]);
468 }
469
470 /**
471 * Function called via JNI to get a list containing the DER encoded certificates
472 * of the user selected certificate chain (beginning with the user certificate).
473 *
474 * Since this method is called from a thread of charon's thread pool we are safe
475 * to call methods on KeyChain directly.
476 *
477 * @return list containing the certificates (first element is the user certificate)
478 * @throws InterruptedException
479 * @throws KeyChainException
480 * @throws CertificateEncodingException
481 */
482 private byte[][] getUserCertificate() throws KeyChainException, InterruptedException, CertificateEncodingException
483 {
484 ArrayList<byte[]> encodings = new ArrayList<byte[]>();
485 X509Certificate[] chain = KeyChain.getCertificateChain(getApplicationContext(), mCurrentUserCertificateAlias);
486 if (chain == null || chain.length == 0)
487 {
488 return null;
489 }
490 for (X509Certificate cert : chain)
491 {
492 encodings.add(cert.getEncoded());
493 }
494 return encodings.toArray(new byte[encodings.size()][]);
495 }
496
497 /**
498 * Function called via JNI to get the private key the user selected.
499 *
500 * Since this method is called from a thread of charon's thread pool we are safe
501 * to call methods on KeyChain directly.
502 *
503 * @return the private key
504 * @throws InterruptedException
505 * @throws KeyChainException
506 * @throws CertificateEncodingException
507 */
508 private PrivateKey getUserKey() throws KeyChainException, InterruptedException
509 {
510 return KeyChain.getPrivateKey(getApplicationContext(), mCurrentUserCertificateAlias);
511
512 }
513
514 /**
515 * Initialization of charon, provided by libandroidbridge.so
516 *
517 * @param builder BuilderAdapter for this connection
518 * @param logfile absolute path to the logfile
519 * @param boyd enable BYOD features
520 */
521 public native void initializeCharon(BuilderAdapter builder, String logfile, boolean byod);
522
523 /**
524 * Deinitialize charon, provided by libandroidbridge.so
525 */
526 public native void deinitializeCharon();
527
528 /**
529 * Initiate VPN, provided by libandroidbridge.so
530 */
531 public native void initiate(String type, String gateway, String username, String password);
532
533 /**
534 * Adapter for VpnService.Builder which is used to access it safely via JNI.
535 * There is a corresponding C object to access it from native code.
536 */
537 public class BuilderAdapter
538 {
539 private final String mName;
540 private VpnService.Builder mBuilder;
541
542 public BuilderAdapter(String name)
543 {
544 mName = name;
545 mBuilder = createBuilder(name);
546 }
547
548 private VpnService.Builder createBuilder(String name)
549 {
550 VpnService.Builder builder = new CharonVpnService.Builder();
551 builder.setSession(mName);
552
553 /* even though the option displayed in the system dialog says "Configure"
554 * we just use our main Activity */
555 Context context = getApplicationContext();
556 Intent intent = new Intent(context, MainActivity.class);
557 PendingIntent pending = PendingIntent.getActivity(context, 0, intent,
558 PendingIntent.FLAG_UPDATE_CURRENT);
559 builder.setConfigureIntent(pending);
560 return builder;
561 }
562
563 public synchronized boolean addAddress(String address, int prefixLength)
564 {
565 try
566 {
567 mBuilder.addAddress(address, prefixLength);
568 }
569 catch (IllegalArgumentException ex)
570 {
571 return false;
572 }
573 return true;
574 }
575
576 public synchronized boolean addDnsServer(String address)
577 {
578 try
579 {
580 mBuilder.addDnsServer(address);
581 }
582 catch (IllegalArgumentException ex)
583 {
584 return false;
585 }
586 return true;
587 }
588
589 public synchronized boolean addRoute(String address, int prefixLength)
590 {
591 try
592 {
593 mBuilder.addRoute(address, prefixLength);
594 }
595 catch (IllegalArgumentException ex)
596 {
597 return false;
598 }
599 return true;
600 }
601
602 public synchronized boolean addSearchDomain(String domain)
603 {
604 try
605 {
606 mBuilder.addSearchDomain(domain);
607 }
608 catch (IllegalArgumentException ex)
609 {
610 return false;
611 }
612 return true;
613 }
614
615 public synchronized boolean setMtu(int mtu)
616 {
617 try
618 {
619 mBuilder.setMtu(mtu);
620 }
621 catch (IllegalArgumentException ex)
622 {
623 return false;
624 }
625 return true;
626 }
627
628 public synchronized int establish()
629 {
630 ParcelFileDescriptor fd;
631 try
632 {
633 fd = mBuilder.establish();
634 }
635 catch (Exception ex)
636 {
637 ex.printStackTrace();
638 return -1;
639 }
640 if (fd == null)
641 {
642 return -1;
643 }
644 /* now that the TUN device is created we don't need the current
645 * builder anymore, but we might need another when reestablishing */
646 mBuilder = createBuilder(mName);
647 return fd.detachFd();
648 }
649 }
650
651 /*
652 * The libraries are extracted to /data/data/org.strongswan.android/...
653 * during installation.
654 */
655 static
656 {
657 System.loadLibrary("crypto");
658 System.loadLibrary("strongswan");
659
660 if (MainActivity.USE_BYOD)
661 {
662 System.loadLibrary("tncif");
663 System.loadLibrary("tnccs");
664 System.loadLibrary("imcv");
665 System.loadLibrary("pts");
666 }
667
668 System.loadLibrary("hydra");
669 System.loadLibrary("charon");
670 System.loadLibrary("ipsec");
671 System.loadLibrary("androidbridge");
672 }
673 }