1a924303722d1172c7f9e07b7ddd5d8f06eee89c
[strongswan.git] / src / frontends / android / jni / libandroidbridge / charonservice.c
1 /*
2 * Copyright (C) 2012 Giuliano Grassi
3 * Copyright (C) 2012 Ralf Sager
4 * Copyright (C) 2012 Tobias Brunner
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 #include <signal.h>
19 #include <string.h>
20 #include <sys/utsname.h>
21 #include <android/log.h>
22 #include <errno.h>
23
24 #include "charonservice.h"
25 #include "android_jni.h"
26 #include "backend/android_attr.h"
27 #include "backend/android_creds.h"
28 #include "backend/android_private_key.h"
29 #include "backend/android_service.h"
30 #include "kernel/android_ipsec.h"
31 #include "kernel/android_net.h"
32
33 #include <daemon.h>
34 #include <hydra.h>
35 #include <ipsec.h>
36 #include <library.h>
37 #include <threading/thread.h>
38
39 #define ANDROID_DEBUG_LEVEL 1
40 #define ANDROID_RETRASNMIT_TRIES 3
41 #define ANDROID_RETRANSMIT_TIMEOUT 2.0
42 #define ANDROID_RETRANSMIT_BASE 1.4
43
44 typedef struct private_charonservice_t private_charonservice_t;
45
46 /**
47 * private data of charonservice
48 */
49 struct private_charonservice_t {
50
51 /**
52 * public interface
53 */
54 charonservice_t public;
55
56 /**
57 * android_attr instance
58 */
59 android_attr_t *attr;
60
61 /**
62 * android_creds instance
63 */
64 android_creds_t *creds;
65
66 /**
67 * android_service instance
68 */
69 android_service_t *service;
70
71 /**
72 * VpnService builder (accessed via JNI)
73 */
74 vpnservice_builder_t *builder;
75
76 /**
77 * NetworkManager instance (accessed via JNI)
78 */
79 network_manager_t *network_manager;
80
81 /**
82 * CharonVpnService reference
83 */
84 jobject vpn_service;
85
86 /**
87 * Sockets that were bypassed and we keep track for
88 */
89 linked_list_t *sockets;
90 };
91
92 /**
93 * Single instance of charonservice_t.
94 */
95 charonservice_t *charonservice;
96
97 /**
98 * hook in library for debugging messages
99 */
100 extern void (*dbg)(debug_t group, level_t level, char *fmt, ...);
101
102 /**
103 * Logging hook for library logs, using android specific logging
104 */
105 static void dbg_android(debug_t group, level_t level, char *fmt, ...)
106 {
107 va_list args;
108
109 if (level <= ANDROID_DEBUG_LEVEL)
110 {
111 char sgroup[16], buffer[8192];
112 char *current = buffer, *next;
113
114 snprintf(sgroup, sizeof(sgroup), "%N", debug_names, group);
115 va_start(args, fmt);
116 vsnprintf(buffer, sizeof(buffer), fmt, args);
117 va_end(args);
118 while (current)
119 { /* log each line separately */
120 next = strchr(current, '\n');
121 if (next)
122 {
123 *(next++) = '\0';
124 }
125 __android_log_print(ANDROID_LOG_INFO, "charon", "00[%s] %s\n",
126 sgroup, current);
127 current = next;
128 }
129 }
130 }
131
132 METHOD(charonservice_t, update_status, bool,
133 private_charonservice_t *this, android_vpn_state_t code)
134 {
135 JNIEnv *env;
136 jmethodID method_id;
137 bool success = FALSE;
138
139 androidjni_attach_thread(&env);
140
141 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
142 "updateStatus", "(I)V");
143 if (!method_id)
144 {
145 goto failed;
146 }
147 (*env)->CallVoidMethod(env, this->vpn_service, method_id, (jint)code);
148 success = !androidjni_exception_occurred(env);
149
150 failed:
151 androidjni_exception_occurred(env);
152 androidjni_detach_thread();
153 return success;
154 }
155
156 /**
157 * Bypass a single socket
158 */
159 static bool bypass_single_socket(intptr_t fd, private_charonservice_t *this)
160 {
161 JNIEnv *env;
162 jmethodID method_id;
163
164 androidjni_attach_thread(&env);
165
166 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
167 "protect", "(I)Z");
168 if (!method_id)
169 {
170 goto failed;
171 }
172 if (!(*env)->CallBooleanMethod(env, this->vpn_service, method_id, fd))
173 {
174 DBG2(DBG_KNL, "VpnService.protect() failed");
175 goto failed;
176 }
177 androidjni_detach_thread();
178 return TRUE;
179
180 failed:
181 androidjni_exception_occurred(env);
182 androidjni_detach_thread();
183 return FALSE;
184 }
185
186 METHOD(charonservice_t, bypass_socket, bool,
187 private_charonservice_t *this, int fd, int family)
188 {
189 if (fd >= 0)
190 {
191 this->sockets->insert_last(this->sockets, (void*)(intptr_t)fd);
192 return bypass_single_socket((intptr_t)fd, this);
193 }
194 this->sockets->invoke_function(this->sockets, (void*)bypass_single_socket,
195 this);
196 return TRUE;
197 }
198
199 /**
200 * Converts the given Java array of byte arrays (byte[][]) to a linked list
201 * of chunk_t objects.
202 */
203 static linked_list_t *convert_array_of_byte_arrays(JNIEnv *env,
204 jobjectArray jarray)
205 {
206 linked_list_t *list;
207 jsize i;
208
209 list = linked_list_create();
210 for (i = 0; i < (*env)->GetArrayLength(env, jarray); ++i)
211 {
212 chunk_t *chunk;
213 jbyteArray jbytearray;
214
215 chunk = malloc_thing(chunk_t);
216 list->insert_last(list, chunk);
217
218 jbytearray = (*env)->GetObjectArrayElement(env, jarray, i);
219 *chunk = chunk_alloc((*env)->GetArrayLength(env, jbytearray));
220 (*env)->GetByteArrayRegion(env, jbytearray, 0, chunk->len, chunk->ptr);
221 (*env)->DeleteLocalRef(env, jbytearray);
222 }
223 return list;
224 }
225
226 METHOD(charonservice_t, get_trusted_certificates, linked_list_t*,
227 private_charonservice_t *this)
228 {
229 JNIEnv *env;
230 jmethodID method_id;
231 jobjectArray jcerts;
232 linked_list_t *list;
233
234 androidjni_attach_thread(&env);
235
236 method_id = (*env)->GetMethodID(env,
237 android_charonvpnservice_class,
238 "getTrustedCertificates", "(Ljava/lang/String;)[[B");
239 if (!method_id)
240 {
241 goto failed;
242 }
243 jcerts = (*env)->CallObjectMethod(env, this->vpn_service, method_id, NULL);
244 if (!jcerts || androidjni_exception_occurred(env))
245 {
246 goto failed;
247 }
248 list = convert_array_of_byte_arrays(env, jcerts);
249 androidjni_detach_thread();
250 return list;
251
252 failed:
253 androidjni_exception_occurred(env);
254 androidjni_detach_thread();
255 return NULL;
256 }
257
258 METHOD(charonservice_t, get_user_certificate, linked_list_t*,
259 private_charonservice_t *this)
260 {
261 JNIEnv *env;
262 jmethodID method_id;
263 jobjectArray jencodings;
264 linked_list_t *list;
265
266 androidjni_attach_thread(&env);
267
268 method_id = (*env)->GetMethodID(env,
269 android_charonvpnservice_class,
270 "getUserCertificate", "()[[B");
271 if (!method_id)
272 {
273 goto failed;
274 }
275 jencodings = (*env)->CallObjectMethod(env, this->vpn_service, method_id);
276 if (!jencodings || androidjni_exception_occurred(env))
277 {
278 goto failed;
279 }
280 list = convert_array_of_byte_arrays(env, jencodings);
281 androidjni_detach_thread();
282 return list;
283
284 failed:
285 androidjni_exception_occurred(env);
286 androidjni_detach_thread();
287 return NULL;
288 }
289
290 METHOD(charonservice_t, get_user_key, private_key_t*,
291 private_charonservice_t *this, public_key_t *pubkey)
292 {
293 JNIEnv *env;
294 jmethodID method_id;
295 private_key_t *key;
296 jobject jkey;
297
298 androidjni_attach_thread(&env);
299
300 method_id = (*env)->GetMethodID(env,
301 android_charonvpnservice_class,
302 "getUserKey", "()Ljava/security/PrivateKey;");
303 if (!method_id)
304 {
305 goto failed;
306 }
307 jkey = (*env)->CallObjectMethod(env, this->vpn_service, method_id);
308 if (!jkey || androidjni_exception_occurred(env))
309 {
310 goto failed;
311 }
312 key = android_private_key_create(jkey, pubkey);
313 androidjni_detach_thread();
314 return key;
315
316 failed:
317 DESTROY_IF(pubkey);
318 androidjni_exception_occurred(env);
319 androidjni_detach_thread();
320 return NULL;
321 }
322
323 METHOD(charonservice_t, get_vpnservice_builder, vpnservice_builder_t*,
324 private_charonservice_t *this)
325 {
326 return this->builder;
327 }
328
329 METHOD(charonservice_t, get_network_manager, network_manager_t*,
330 private_charonservice_t *this)
331 {
332 return this->network_manager;
333 }
334
335 /**
336 * Initiate a new connection
337 *
338 * @param gateway gateway address (gets owned)
339 * @param username username (gets owned)
340 * @param password password (gets owned)
341 */
342 static void initiate(char *type, char *gateway, char *username, char *password)
343 {
344 private_charonservice_t *this = (private_charonservice_t*)charonservice;
345
346 this->creds->clear(this->creds);
347 DESTROY_IF(this->service);
348 this->service = android_service_create(this->creds, type, gateway,
349 username, password);
350 }
351
352 /**
353 * Initialize/deinitialize Android backend
354 */
355 static bool charonservice_register(void *plugin, plugin_feature_t *feature,
356 bool reg, void *data)
357 {
358 private_charonservice_t *this = (private_charonservice_t*)charonservice;
359 if (reg)
360 {
361 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
362 hydra->attributes->add_handler(hydra->attributes,
363 &this->attr->handler);
364 }
365 else
366 {
367 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
368 hydra->attributes->remove_handler(hydra->attributes,
369 &this->attr->handler);
370 if (this->service)
371 {
372 this->service->destroy(this->service);
373 this->service = NULL;
374 }
375 }
376 return TRUE;
377 }
378
379 /**
380 * Initialize the charonservice object
381 */
382 static void charonservice_init(JNIEnv *env, jobject service, jobject builder,
383 char *logfile)
384 {
385 private_charonservice_t *this;
386 static plugin_feature_t features[] = {
387 PLUGIN_CALLBACK(kernel_net_register, kernel_android_net_create),
388 PLUGIN_PROVIDE(CUSTOM, "kernel-net"),
389 PLUGIN_CALLBACK(kernel_ipsec_register, kernel_android_ipsec_create),
390 PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
391 PLUGIN_CALLBACK((plugin_feature_callback_t)charonservice_register, NULL),
392 PLUGIN_PROVIDE(CUSTOM, "Android backend"),
393 PLUGIN_DEPENDS(CUSTOM, "libcharon"),
394 };
395
396 INIT(this,
397 .public = {
398 .update_status = _update_status,
399 .bypass_socket = _bypass_socket,
400 .get_trusted_certificates = _get_trusted_certificates,
401 .get_user_certificate = _get_user_certificate,
402 .get_user_key = _get_user_key,
403 .get_vpnservice_builder = _get_vpnservice_builder,
404 .get_network_manager = _get_network_manager,
405 },
406 .attr = android_attr_create(),
407 .creds = android_creds_create(),
408 .builder = vpnservice_builder_create(builder),
409 .network_manager = network_manager_create(service),
410 .sockets = linked_list_create(),
411 .vpn_service = (*env)->NewGlobalRef(env, service),
412 );
413 charonservice = &this->public;
414
415 lib->plugins->add_static_features(lib->plugins, "androidbridge", features,
416 countof(features), TRUE);
417
418 lib->settings->set_int(lib->settings,
419 "charon.plugins.android_log.loglevel", ANDROID_DEBUG_LEVEL);
420 /* setup file logger */
421 lib->settings->set_str(lib->settings,
422 "charon.filelog.%s.time_format", "%b %e %T", logfile);
423 lib->settings->set_bool(lib->settings,
424 "charon.filelog.%s.append", FALSE, logfile);
425 lib->settings->set_bool(lib->settings,
426 "charon.filelog.%s.flush_line", TRUE, logfile);
427 lib->settings->set_int(lib->settings,
428 "charon.filelog.%s.default", ANDROID_DEBUG_LEVEL, logfile);
429
430 lib->settings->set_int(lib->settings,
431 "charon.retransmit_tries", ANDROID_RETRASNMIT_TRIES);
432 lib->settings->set_double(lib->settings,
433 "charon.retransmit_timeout", ANDROID_RETRANSMIT_TIMEOUT);
434 lib->settings->set_double(lib->settings,
435 "charon.retransmit_base", ANDROID_RETRANSMIT_BASE);
436 lib->settings->set_bool(lib->settings,
437 "charon.close_ike_on_child_failure", TRUE);
438 /* setting the source address breaks the VpnService.protect() function which
439 * uses SO_BINDTODEVICE internally. the addresses provided to the kernel as
440 * auxiliary data have precedence over this option causing a routing loop if
441 * the gateway is contained in the VPN routes. alternatively, providing an
442 * explicit device (in addition or instead of the source address) in the
443 * auxiliary data would also work, but we currently don't have that
444 * information */
445 lib->settings->set_bool(lib->settings,
446 "charon.plugins.socket-default.set_source", FALSE);
447 }
448
449 /**
450 * Deinitialize the charonservice object
451 */
452 static void charonservice_deinit(JNIEnv *env)
453 {
454 private_charonservice_t *this = (private_charonservice_t*)charonservice;
455
456 this->network_manager->destroy(this->network_manager);
457 this->sockets->destroy(this->sockets);
458 this->builder->destroy(this->builder);
459 this->creds->destroy(this->creds);
460 this->attr->destroy(this->attr);
461 (*env)->DeleteGlobalRef(env, this->vpn_service);
462 free(this);
463 charonservice = NULL;
464 }
465
466 /**
467 * Handle SIGSEGV/SIGILL signals raised by threads
468 */
469 static void segv_handler(int signal)
470 {
471 dbg_android(DBG_DMN, 1, "thread %u received %d", thread_current_id(),
472 signal);
473 exit(1);
474 }
475
476 /**
477 * Initialize charon and the libraries via JNI
478 */
479 JNI_METHOD(CharonVpnService, initializeCharon, void,
480 jobject builder, jstring jlogfile)
481 {
482 struct sigaction action;
483 struct utsname utsname;
484 char *logfile;
485
486 /* logging for library during initialization, as we have no bus yet */
487 dbg = dbg_android;
488
489 /* initialize library */
490 if (!library_init(NULL))
491 {
492 library_deinit();
493 return;
494 }
495
496 if (!libhydra_init("charon"))
497 {
498 libhydra_deinit();
499 library_deinit();
500 return;
501 }
502
503 if (!libipsec_init())
504 {
505 libipsec_deinit();
506 libhydra_deinit();
507 library_deinit();
508 return;
509 }
510
511 if (!libcharon_init("charon"))
512 {
513 libcharon_deinit();
514 libipsec_deinit();
515 libhydra_deinit();
516 library_deinit();
517 return;
518 }
519
520 logfile = androidjni_convert_jstring(env, jlogfile);
521 charonservice_init(env, this, builder, logfile);
522 free(logfile);
523
524 charon->load_loggers(charon, NULL, FALSE);
525
526 if (uname(&utsname) != 0)
527 {
528 memset(&utsname, 0, sizeof(utsname));
529 }
530 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
531 utsname.sysname, utsname.release, utsname.machine);
532
533 if (!charon->initialize(charon, PLUGINS))
534 {
535 libcharon_deinit();
536 charonservice_deinit(env);
537 libipsec_deinit();
538 libhydra_deinit();
539 library_deinit();
540 return;
541 }
542
543 /* add handler for SEGV and ILL etc. */
544 action.sa_handler = segv_handler;
545 action.sa_flags = 0;
546 sigemptyset(&action.sa_mask);
547 sigaction(SIGSEGV, &action, NULL);
548 sigaction(SIGILL, &action, NULL);
549 sigaction(SIGBUS, &action, NULL);
550 action.sa_handler = SIG_IGN;
551 sigaction(SIGPIPE, &action, NULL);
552
553 /* start daemon (i.e. the threads in the thread-pool) */
554 charon->start(charon);
555 }
556
557 /**
558 * Deinitialize charon and all libraries
559 */
560 JNI_METHOD(CharonVpnService, deinitializeCharon, void)
561 {
562 /* deinitialize charon before we destroy our own objects */
563 libcharon_deinit();
564 charonservice_deinit(env);
565 libipsec_deinit();
566 libhydra_deinit();
567 library_deinit();
568 }
569
570 /**
571 * Initiate SA
572 */
573 JNI_METHOD(CharonVpnService, initiate, void,
574 jstring jtype, jstring jgateway, jstring jusername, jstring jpassword)
575 {
576 char *type, *gateway, *username, *password;
577
578 type = androidjni_convert_jstring(env, jtype);
579 gateway = androidjni_convert_jstring(env, jgateway);
580 username = androidjni_convert_jstring(env, jusername);
581 password = androidjni_convert_jstring(env, jpassword);
582
583 initiate(type, gateway, username, password);
584 }