Adapter class added around VpnService.Builder which allows to access it via JNI
[strongswan.git] / src / frontends / android / src / org / strongswan / android / logic / CharonVpnService.java
1 /*
2 * Copyright (C) 2012 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.net.InetAddress;
21 import java.net.NetworkInterface;
22 import java.net.SocketException;
23 import java.security.cert.CertificateEncodingException;
24 import java.security.cert.X509Certificate;
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27
28 import org.strongswan.android.data.VpnProfile;
29 import org.strongswan.android.data.VpnProfileDataSource;
30 import org.strongswan.android.logic.VpnStateService.ErrorState;
31 import org.strongswan.android.logic.VpnStateService.State;
32
33 import android.app.Service;
34 import android.content.ComponentName;
35 import android.content.Intent;
36 import android.content.ServiceConnection;
37 import android.net.VpnService;
38 import android.os.Bundle;
39 import android.os.IBinder;
40 import android.os.ParcelFileDescriptor;
41 import android.util.Log;
42
43 public class CharonVpnService extends VpnService implements Runnable
44 {
45 private static final String TAG = CharonVpnService.class.getSimpleName();
46 private VpnProfileDataSource mDataSource;
47 private Thread mConnectionHandler;
48 private VpnProfile mCurrentProfile;
49 private VpnProfile mNextProfile;
50 private volatile boolean mProfileUpdated;
51 private volatile boolean mTerminate;
52 private VpnStateService mService;
53 private final Object mServiceLock = new Object();
54 private final ServiceConnection mServiceConnection = new ServiceConnection() {
55 @Override
56 public void onServiceDisconnected(ComponentName name)
57 { /* since the service is local this is theoretically only called when the process is terminated */
58 synchronized (mServiceLock)
59 {
60 mService = null;
61 }
62 }
63
64 @Override
65 public void onServiceConnected(ComponentName name, IBinder service)
66 {
67 synchronized (mServiceLock)
68 {
69 mService = ((VpnStateService.LocalBinder)service).getService();
70 }
71 /* we are now ready to start the handler thread */
72 mConnectionHandler.start();
73 }
74 };
75
76 /**
77 * as defined in charonservice.h
78 */
79 static final int STATE_CHILD_SA_UP = 1;
80 static final int STATE_CHILD_SA_DOWN = 2;
81 static final int STATE_AUTH_ERROR = 3;
82 static final int STATE_PEER_AUTH_ERROR = 4;
83 static final int STATE_LOOKUP_ERROR = 5;
84 static final int STATE_UNREACHABLE_ERROR = 6;
85 static final int STATE_GENERIC_ERROR = 7;
86
87 @Override
88 public int onStartCommand(Intent intent, int flags, int startId)
89 {
90 if (intent != null)
91 {
92 Bundle bundle = intent.getExtras();
93 VpnProfile profile = null;
94 if (bundle != null)
95 {
96 profile = mDataSource.getVpnProfile(bundle.getLong(VpnProfileDataSource.KEY_ID));
97 if (profile != null)
98 {
99 String password = bundle.getString(VpnProfileDataSource.KEY_PASSWORD);
100 profile.setPassword(password);
101 }
102 }
103 setNextProfile(profile);
104 }
105 return START_NOT_STICKY;
106 }
107
108 @Override
109 public void onCreate()
110 {
111 mDataSource = new VpnProfileDataSource(this);
112 mDataSource.open();
113 /* use a separate thread as main thread for charon */
114 mConnectionHandler = new Thread(this);
115 /* the thread is started when the service is bound */
116 bindService(new Intent(this, VpnStateService.class),
117 mServiceConnection, Service.BIND_AUTO_CREATE);
118 }
119
120 @Override
121 public void onRevoke()
122 { /* the system revoked the rights grated with the initial prepare() call.
123 * called when the user clicks disconnect in the system's VPN dialog */
124 setNextProfile(null);
125 }
126
127 @Override
128 public void onDestroy()
129 {
130 mTerminate = true;
131 setNextProfile(null);
132 try
133 {
134 mConnectionHandler.join();
135 }
136 catch (InterruptedException e)
137 {
138 e.printStackTrace();
139 }
140 if (mService != null)
141 {
142 unbindService(mServiceConnection);
143 }
144 mDataSource.close();
145 }
146
147 /**
148 * Set the profile that is to be initiated next. Notify the handler thread.
149 *
150 * @param profile the profile to initiate
151 */
152 private void setNextProfile(VpnProfile profile)
153 {
154 synchronized (this)
155 {
156 this.mNextProfile = profile;
157 mProfileUpdated = true;
158 notifyAll();
159 }
160 }
161
162 @Override
163 public void run()
164 {
165 while (true)
166 {
167 synchronized (this)
168 {
169 try
170 {
171 while (!mProfileUpdated)
172 {
173 wait();
174 }
175
176 mProfileUpdated = false;
177 stopCurrentConnection();
178 if (mNextProfile == null)
179 {
180 setProfile(null);
181 setState(State.DISABLED);
182 if (mTerminate)
183 {
184 break;
185 }
186 }
187 else
188 {
189 mCurrentProfile = mNextProfile;
190 mNextProfile = null;
191
192 setProfile(mCurrentProfile);
193 setError(ErrorState.NO_ERROR);
194 setState(State.CONNECTING);
195
196 initializeCharon();
197 Log.i(TAG, "charon started");
198
199 String local_address = getLocalIPv4Address();
200 initiate(local_address != null ? local_address : "0.0.0.0",
201 mCurrentProfile.getGateway(), mCurrentProfile.getUsername(),
202 mCurrentProfile.getPassword());
203 }
204 }
205 catch (InterruptedException ex)
206 {
207 stopCurrentConnection();
208 setState(State.DISABLED);
209 }
210 }
211 }
212 }
213
214 /**
215 * Stop any existing connection by deinitializing charon.
216 */
217 private void stopCurrentConnection()
218 {
219 synchronized (this)
220 {
221 if (mCurrentProfile != null)
222 {
223 setState(State.DISCONNECTING);
224 deinitializeCharon();
225 Log.i(TAG, "charon stopped");
226 mCurrentProfile = null;
227 }
228 }
229 }
230
231 /**
232 * Update the VPN profile on the state service. Called by the handler thread.
233 *
234 * @param profile currently active VPN profile
235 */
236 private void setProfile(VpnProfile profile)
237 {
238 synchronized (mServiceLock)
239 {
240 if (mService != null)
241 {
242 mService.setProfile(profile);
243 }
244 }
245 }
246
247 /**
248 * Update the current VPN state on the state service. Called by the handler
249 * thread and any of charon's threads.
250 *
251 * @param state current state
252 */
253 private void setState(State state)
254 {
255 synchronized (mServiceLock)
256 {
257 if (mService != null)
258 {
259 mService.setState(state);
260 }
261 }
262 }
263
264 /**
265 * Set an error on the state service. Called by the handler thread and any
266 * of charon's threads.
267 *
268 * @param error error state
269 */
270 private void setError(ErrorState error)
271 {
272 synchronized (mServiceLock)
273 {
274 if (mService != null)
275 {
276 mService.setError(error);
277 }
278 }
279 }
280
281 /**
282 * Set an error on the state service and disconnect the current connection.
283 * This is not done by calling stopCurrentConnection() above, but instead
284 * is done asynchronously via state service.
285 *
286 * @param error error state
287 */
288 private void setErrorDisconnect(ErrorState error)
289 {
290 synchronized (mServiceLock)
291 {
292 if (mService != null)
293 {
294 mService.setError(error);
295 mService.disconnect();
296 }
297 }
298 }
299
300 /**
301 * Updates the state of the current connection.
302 * Called via JNI by different threads (but not concurrently).
303 *
304 * @param status new state
305 */
306 public void updateStatus(int status)
307 {
308 switch (status)
309 {
310 case STATE_CHILD_SA_DOWN:
311 synchronized (mServiceLock)
312 {
313 /* since this state is also reached when the SA is closed remotely,
314 * we call disconnect() to make sure charon is properly deinitialized */
315 if (mService != null)
316 {
317 mService.disconnect();
318 }
319 }
320 break;
321 case STATE_CHILD_SA_UP:
322 setState(State.CONNECTED);
323 break;
324 case STATE_AUTH_ERROR:
325 setErrorDisconnect(ErrorState.AUTH_FAILED);
326 break;
327 case STATE_PEER_AUTH_ERROR:
328 setErrorDisconnect(ErrorState.PEER_AUTH_FAILED);
329 break;
330 case STATE_LOOKUP_ERROR:
331 setErrorDisconnect(ErrorState.LOOKUP_FAILED);
332 break;
333 case STATE_UNREACHABLE_ERROR:
334 setErrorDisconnect(ErrorState.UNREACHABLE);
335 break;
336 case STATE_GENERIC_ERROR:
337 setErrorDisconnect(ErrorState.GENERIC_ERROR);
338 break;
339 default:
340 Log.e(TAG, "Unknown status code received");
341 break;
342 }
343 }
344
345 /**
346 * Function called via JNI to generate a list of DER encoded CA certificates
347 * as byte array.
348 *
349 * @param hash optional alias (only hash part), if given matching certificates are returned
350 * @return a list of DER encoded CA certificates
351 */
352 private synchronized byte[][] getTrustedCertificates(String hash)
353 {
354 ArrayList<byte[]> certs = new ArrayList<byte[]>();
355 TrustedCertificateManager certman = TrustedCertificateManager.getInstance();
356 try
357 {
358 if (hash != null)
359 {
360 String alias = "user:" + hash + ".0";
361 X509Certificate cert = certman.getCACertificateFromAlias(alias);
362 if (cert == null)
363 {
364 alias = "system:" + hash + ".0";
365 cert = certman.getCACertificateFromAlias(alias);
366 }
367 if (cert == null)
368 {
369 return null;
370 }
371 certs.add(cert.getEncoded());
372 }
373 else
374 {
375 String alias = this.mCurrentProfile.getCertificateAlias();
376 if (alias != null)
377 {
378 X509Certificate cert = certman.getCACertificateFromAlias(alias);
379 if (cert == null)
380 {
381 return null;
382 }
383 certs.add(cert.getEncoded());
384 }
385 else
386 {
387 for (X509Certificate cert : certman.getAllCACertificates().values())
388 {
389 certs.add(cert.getEncoded());
390 }
391 }
392 }
393 }
394 catch (CertificateEncodingException e)
395 {
396 e.printStackTrace();
397 return null;
398 }
399 return certs.toArray(new byte[certs.size()][]);
400 }
401
402 /**
403 * Initialization of charon, provided by libandroidbridge.so
404 */
405 public native void initializeCharon();
406
407 /**
408 * Deinitialize charon, provided by libandroidbridge.so
409 */
410 public native void deinitializeCharon();
411
412 /**
413 * Initiate VPN, provided by libandroidbridge.so
414 */
415 public native void initiate(String local_address, String gateway,
416 String username, String password);
417
418 /**
419 * Helper function that retrieves a local IPv4 address.
420 *
421 * @return string representation of an IPv4 address, or null if none found
422 */
423 private static String getLocalIPv4Address()
424 {
425 try
426 {
427 Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
428 while (en.hasMoreElements())
429 {
430 NetworkInterface intf = en.nextElement();
431
432 Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
433 while (enumIpAddr.hasMoreElements())
434 {
435 InetAddress inetAddress = enumIpAddr.nextElement();
436 if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4)
437 {
438 return inetAddress.getHostAddress().toString();
439 }
440 }
441 }
442 }
443 catch (SocketException ex)
444 {
445 ex.printStackTrace();
446 return null;
447 }
448 return null;
449 }
450
451 /**
452 * Adapter for VpnService.Builder which is used to access it safely via JNI.
453 */
454 public class BuilderAdapter
455 {
456 VpnService.Builder builder;
457
458 public BuilderAdapter(String name)
459 {
460 builder = new CharonVpnService.Builder();
461 builder.setSession(name);
462 }
463
464 public synchronized boolean addAddress(String address, int prefixLength)
465 {
466 try
467 {
468 builder.addAddress(address, prefixLength);
469 }
470 catch (IllegalArgumentException ex)
471 {
472 return false;
473 }
474 return true;
475 }
476
477 public synchronized boolean addDnsServer(String address)
478 {
479 try
480 {
481 builder.addDnsServer(address);
482 }
483 catch (IllegalArgumentException ex)
484 {
485 return false;
486 }
487 return true;
488 }
489
490 public synchronized boolean addRoute(String address, int prefixLength)
491 {
492 try
493 {
494 builder.addRoute(address, prefixLength);
495 }
496 catch (IllegalArgumentException ex)
497 {
498 return false;
499 }
500 return true;
501 }
502
503 public synchronized boolean addSearchDomain(String domain)
504 {
505 try
506 {
507 builder.addSearchDomain(domain);
508 }
509 catch (IllegalArgumentException ex)
510 {
511 return false;
512 }
513 return true;
514 }
515
516 public synchronized boolean setMtu(int mtu)
517 {
518 try
519 {
520 builder.setMtu(mtu);
521 }
522 catch (IllegalArgumentException ex)
523 {
524 return false;
525 }
526 return true;
527 }
528
529 public synchronized int establish()
530 {
531 ParcelFileDescriptor fd;
532 try
533 {
534 fd = builder.establish();
535 }
536 catch (Exception ex)
537 {
538 ex.printStackTrace();
539 return -1;
540 }
541 if (fd == null)
542 {
543 return -1;
544 }
545 return fd.detachFd();
546 }
547 }
548
549 /*
550 * The libraries are extracted to /data/data/org.strongswan.android/...
551 * during installation.
552 */
553 static
554 {
555 System.loadLibrary("crypto");
556 System.loadLibrary("strongswan");
557 System.loadLibrary("hydra");
558 System.loadLibrary("charon");
559 System.loadLibrary("ipsec");
560 System.loadLibrary("androidbridge");
561 }
562 }