5b4d649ae1194a79c70dc731d858b52f8d9c997e
[strongswan.git] / src / frontends / android / jni / libandroidbridge / charonservice.c
1 /*
2 * Copyright (C) 2012-2015 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 #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 #ifdef USE_BYOD
34 #include "byod/imc_android.h"
35 #endif
36
37 #include <daemon.h>
38 #include <hydra.h>
39 #include <ipsec.h>
40 #include <library.h>
41 #include <threading/thread.h>
42
43 #define ANDROID_DEBUG_LEVEL 1
44 #define ANDROID_RETRASNMIT_TRIES 3
45 #define ANDROID_RETRANSMIT_TIMEOUT 2.0
46 #define ANDROID_RETRANSMIT_BASE 1.4
47 #define ANDROID_FRAGMENT_SIZE 1400
48
49 typedef struct private_charonservice_t private_charonservice_t;
50
51 /**
52 * private data of charonservice
53 */
54 struct private_charonservice_t {
55
56 /**
57 * public interface
58 */
59 charonservice_t public;
60
61 /**
62 * android_attr instance
63 */
64 android_attr_t *attr;
65
66 /**
67 * android_creds instance
68 */
69 android_creds_t *creds;
70
71 /**
72 * android_service instance
73 */
74 android_service_t *service;
75
76 /**
77 * VpnService builder (accessed via JNI)
78 */
79 vpnservice_builder_t *builder;
80
81 /**
82 * NetworkManager instance (accessed via JNI)
83 */
84 network_manager_t *network_manager;
85
86 /**
87 * Handle network events
88 */
89 android_net_t *net_handler;
90
91 /**
92 * CharonVpnService reference
93 */
94 jobject vpn_service;
95
96 /**
97 * Sockets that were bypassed and we keep track for
98 */
99 linked_list_t *sockets;
100 };
101
102 /**
103 * Single instance of charonservice_t.
104 */
105 charonservice_t *charonservice;
106
107 /**
108 * hook in library for debugging messages
109 */
110 extern void (*dbg)(debug_t group, level_t level, char *fmt, ...);
111
112 /**
113 * Logging hook for library logs, using android specific logging
114 */
115 static void dbg_android(debug_t group, level_t level, char *fmt, ...)
116 {
117 va_list args;
118
119 if (level <= ANDROID_DEBUG_LEVEL)
120 {
121 char sgroup[16], buffer[8192];
122 char *current = buffer, *next;
123
124 snprintf(sgroup, sizeof(sgroup), "%N", debug_names, group);
125 va_start(args, fmt);
126 vsnprintf(buffer, sizeof(buffer), fmt, args);
127 va_end(args);
128 while (current)
129 { /* log each line separately */
130 next = strchr(current, '\n');
131 if (next)
132 {
133 *(next++) = '\0';
134 }
135 __android_log_print(ANDROID_LOG_INFO, "charon", "00[%s] %s\n",
136 sgroup, current);
137 current = next;
138 }
139 }
140 }
141
142 METHOD(charonservice_t, update_status, bool,
143 private_charonservice_t *this, android_vpn_state_t code)
144 {
145 JNIEnv *env;
146 jmethodID method_id;
147 bool success = FALSE;
148
149 androidjni_attach_thread(&env);
150
151 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
152 "updateStatus", "(I)V");
153 if (!method_id)
154 {
155 goto failed;
156 }
157 (*env)->CallVoidMethod(env, this->vpn_service, method_id, (jint)code);
158 success = !androidjni_exception_occurred(env);
159
160 failed:
161 androidjni_exception_occurred(env);
162 androidjni_detach_thread();
163 return success;
164 }
165
166 METHOD(charonservice_t, update_imc_state, bool,
167 private_charonservice_t *this, android_imc_state_t state)
168 {
169 JNIEnv *env;
170 jmethodID method_id;
171 bool success = FALSE;
172
173 androidjni_attach_thread(&env);
174
175 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
176 "updateImcState", "(I)V");
177 if (!method_id)
178 {
179 goto failed;
180 }
181 (*env)->CallVoidMethod(env, this->vpn_service, method_id, (jint)state);
182 success = !androidjni_exception_occurred(env);
183
184 failed:
185 androidjni_exception_occurred(env);
186 androidjni_detach_thread();
187 return success;
188 }
189
190 METHOD(charonservice_t, add_remediation_instr, bool,
191 private_charonservice_t *this, char *instr)
192 {
193 JNIEnv *env;
194 jmethodID method_id;
195 jstring jinstr;
196 bool success = FALSE;
197
198 androidjni_attach_thread(&env);
199
200 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
201 "addRemediationInstruction",
202 "(Ljava/lang/String;)V");
203 if (!method_id)
204 {
205 goto failed;
206 }
207 jinstr = (*env)->NewStringUTF(env, instr);
208 if (!jinstr)
209 {
210 goto failed;
211 }
212 (*env)->CallVoidMethod(env, this->vpn_service, method_id, jinstr);
213 success = !androidjni_exception_occurred(env);
214
215 failed:
216 androidjni_exception_occurred(env);
217 androidjni_detach_thread();
218 return success;
219 }
220
221 /**
222 * Bypass a single socket
223 */
224 static bool bypass_single_socket(intptr_t fd, private_charonservice_t *this)
225 {
226 JNIEnv *env;
227 jmethodID method_id;
228
229 androidjni_attach_thread(&env);
230
231 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
232 "protect", "(I)Z");
233 if (!method_id)
234 {
235 goto failed;
236 }
237 if (!(*env)->CallBooleanMethod(env, this->vpn_service, method_id, fd))
238 {
239 DBG2(DBG_KNL, "VpnService.protect() failed");
240 goto failed;
241 }
242 androidjni_detach_thread();
243 return TRUE;
244
245 failed:
246 androidjni_exception_occurred(env);
247 androidjni_detach_thread();
248 return FALSE;
249 }
250
251 METHOD(charonservice_t, bypass_socket, bool,
252 private_charonservice_t *this, int fd, int family)
253 {
254 if (fd >= 0)
255 {
256 this->sockets->insert_last(this->sockets, (void*)(intptr_t)fd);
257 return bypass_single_socket((intptr_t)fd, this);
258 }
259 this->sockets->invoke_function(this->sockets, (void*)bypass_single_socket,
260 this);
261 return TRUE;
262 }
263
264 /**
265 * Converts the given Java array of byte arrays (byte[][]) to a linked list
266 * of chunk_t objects.
267 */
268 static linked_list_t *convert_array_of_byte_arrays(JNIEnv *env,
269 jobjectArray jarray)
270 {
271 linked_list_t *list;
272 jsize i;
273
274 list = linked_list_create();
275 for (i = 0; i < (*env)->GetArrayLength(env, jarray); ++i)
276 {
277 chunk_t *chunk;
278 jbyteArray jbytearray;
279
280 chunk = malloc_thing(chunk_t);
281 list->insert_last(list, chunk);
282
283 jbytearray = (*env)->GetObjectArrayElement(env, jarray, i);
284 *chunk = chunk_alloc((*env)->GetArrayLength(env, jbytearray));
285 (*env)->GetByteArrayRegion(env, jbytearray, 0, chunk->len, chunk->ptr);
286 (*env)->DeleteLocalRef(env, jbytearray);
287 }
288 return list;
289 }
290
291 METHOD(charonservice_t, get_trusted_certificates, linked_list_t*,
292 private_charonservice_t *this)
293 {
294 JNIEnv *env;
295 jmethodID method_id;
296 jobjectArray jcerts;
297 linked_list_t *list;
298
299 androidjni_attach_thread(&env);
300
301 method_id = (*env)->GetMethodID(env,
302 android_charonvpnservice_class,
303 "getTrustedCertificates", "()[[B");
304 if (!method_id)
305 {
306 goto failed;
307 }
308 jcerts = (*env)->CallObjectMethod(env, this->vpn_service, method_id);
309 if (!jcerts || androidjni_exception_occurred(env))
310 {
311 goto failed;
312 }
313 list = convert_array_of_byte_arrays(env, jcerts);
314 androidjni_detach_thread();
315 return list;
316
317 failed:
318 androidjni_exception_occurred(env);
319 androidjni_detach_thread();
320 return NULL;
321 }
322
323 METHOD(charonservice_t, get_user_certificate, linked_list_t*,
324 private_charonservice_t *this)
325 {
326 JNIEnv *env;
327 jmethodID method_id;
328 jobjectArray jencodings;
329 linked_list_t *list;
330
331 androidjni_attach_thread(&env);
332
333 method_id = (*env)->GetMethodID(env,
334 android_charonvpnservice_class,
335 "getUserCertificate", "()[[B");
336 if (!method_id)
337 {
338 goto failed;
339 }
340 jencodings = (*env)->CallObjectMethod(env, this->vpn_service, method_id);
341 if (!jencodings || androidjni_exception_occurred(env))
342 {
343 goto failed;
344 }
345 list = convert_array_of_byte_arrays(env, jencodings);
346 androidjni_detach_thread();
347 return list;
348
349 failed:
350 androidjni_exception_occurred(env);
351 androidjni_detach_thread();
352 return NULL;
353 }
354
355 METHOD(charonservice_t, get_user_key, private_key_t*,
356 private_charonservice_t *this, public_key_t *pubkey)
357 {
358 JNIEnv *env;
359 jmethodID method_id;
360 private_key_t *key;
361 jobject jkey;
362
363 androidjni_attach_thread(&env);
364
365 method_id = (*env)->GetMethodID(env,
366 android_charonvpnservice_class,
367 "getUserKey", "()Ljava/security/PrivateKey;");
368 if (!method_id)
369 {
370 goto failed;
371 }
372 jkey = (*env)->CallObjectMethod(env, this->vpn_service, method_id);
373 if (!jkey || androidjni_exception_occurred(env))
374 {
375 goto failed;
376 }
377 key = android_private_key_create(jkey, pubkey);
378 androidjni_detach_thread();
379 return key;
380
381 failed:
382 DESTROY_IF(pubkey);
383 androidjni_exception_occurred(env);
384 androidjni_detach_thread();
385 return NULL;
386 }
387
388 METHOD(charonservice_t, get_vpnservice_builder, vpnservice_builder_t*,
389 private_charonservice_t *this)
390 {
391 return this->builder;
392 }
393
394 METHOD(charonservice_t, get_network_manager, network_manager_t*,
395 private_charonservice_t *this)
396 {
397 return this->network_manager;
398 }
399
400 /**
401 * Initiate a new connection
402 *
403 * @param settings configuration settings (gets owned)
404 */
405 static void initiate(settings_t *settings)
406 {
407 private_charonservice_t *this = (private_charonservice_t*)charonservice;
408
409 lib->settings->set_str(lib->settings,
410 "charon.plugins.tnc-imc.preferred_language",
411 settings->get_str(settings, "global.language", "en"));
412
413 this->creds->clear(this->creds);
414 DESTROY_IF(this->service);
415 this->service = android_service_create(this->creds, settings);
416 }
417
418 /**
419 * Initialize/deinitialize Android backend
420 */
421 static bool charonservice_register(plugin_t *plugin, plugin_feature_t *feature,
422 bool reg, void *data)
423 {
424 private_charonservice_t *this = (private_charonservice_t*)charonservice;
425 if (reg)
426 {
427 this->net_handler = android_net_create();
428 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
429 charon->attributes->add_handler(charon->attributes,
430 &this->attr->handler);
431 }
432 else
433 {
434 this->net_handler->destroy(this->net_handler);
435 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
436 charon->attributes->remove_handler(charon->attributes,
437 &this->attr->handler);
438 if (this->service)
439 {
440 this->service->destroy(this->service);
441 this->service = NULL;
442 }
443 }
444 return TRUE;
445 }
446
447 /**
448 * Set strongswan.conf options
449 */
450 static void set_options(char *logfile)
451 {
452 lib->settings->set_int(lib->settings,
453 "charon.plugins.android_log.loglevel", ANDROID_DEBUG_LEVEL);
454 /* setup file logger */
455 lib->settings->set_str(lib->settings,
456 "charon.filelog.%s.time_format", "%b %e %T", logfile);
457 lib->settings->set_bool(lib->settings,
458 "charon.filelog.%s.append", FALSE, logfile);
459 lib->settings->set_bool(lib->settings,
460 "charon.filelog.%s.flush_line", TRUE, logfile);
461 lib->settings->set_int(lib->settings,
462 "charon.filelog.%s.default", ANDROID_DEBUG_LEVEL, logfile);
463
464 lib->settings->set_int(lib->settings,
465 "charon.retransmit_tries", ANDROID_RETRASNMIT_TRIES);
466 lib->settings->set_double(lib->settings,
467 "charon.retransmit_timeout", ANDROID_RETRANSMIT_TIMEOUT);
468 lib->settings->set_double(lib->settings,
469 "charon.retransmit_base", ANDROID_RETRANSMIT_BASE);
470 lib->settings->set_int(lib->settings,
471 "charon.fragment_size", ANDROID_FRAGMENT_SIZE);
472 lib->settings->set_bool(lib->settings,
473 "charon.initiator_only", TRUE);
474 lib->settings->set_bool(lib->settings,
475 "charon.close_ike_on_child_failure", TRUE);
476 /* setting the source address breaks the VpnService.protect() function which
477 * uses SO_BINDTODEVICE internally. the addresses provided to the kernel as
478 * auxiliary data have precedence over this option causing a routing loop if
479 * the gateway is contained in the VPN routes. alternatively, providing an
480 * explicit device (in addition or instead of the source address) in the
481 * auxiliary data would also work, but we currently don't have that
482 * information */
483 lib->settings->set_bool(lib->settings,
484 "charon.plugins.socket-default.set_source", FALSE);
485 /* the Linux kernel does currently not support UDP encaspulation for IPv6
486 * so lets disable IPv6 for now to avoid issues with dual-stack gateways */
487 lib->settings->set_bool(lib->settings,
488 "charon.plugins.socket-default.use_ipv6", FALSE);
489 /* don't install virtual IPs via kernel-netlink */
490 lib->settings->set_bool(lib->settings,
491 "charon.install_virtual_ip", FALSE);
492 /* kernel-netlink should not trigger roam events, we use Android's
493 * ConnectivityManager for that, much less noise */
494 lib->settings->set_bool(lib->settings,
495 "charon.plugins.kernel-netlink.roam_events", FALSE);
496 /* ignore tun devices (it's mostly tun0 but it may already be taken, ignore
497 * some others too), also ignore lo as a default route points to it when
498 * no connectivity is available */
499 lib->settings->set_str(lib->settings,
500 "charon.interfaces_ignore", "lo, tun0, tun1, tun2, tun3, "
501 "tun4");
502
503 #ifdef USE_BYOD
504 lib->settings->set_str(lib->settings,
505 "charon.plugins.eap-tnc.protocol", "tnccs-2.0");
506 lib->settings->set_int(lib->settings,
507 "charon.plugins.eap-ttls.max_message_count", 0);
508 lib->settings->set_bool(lib->settings,
509 "android.imc.send_os_info", TRUE);
510 lib->settings->set_str(lib->settings,
511 "libtnccs.tnc_config", "");
512 #endif
513 }
514
515 /**
516 * Initialize the charonservice object
517 */
518 static void charonservice_init(JNIEnv *env, jobject service, jobject builder,
519 jboolean byod)
520 {
521 private_charonservice_t *this;
522 static plugin_feature_t features[] = {
523 PLUGIN_CALLBACK(kernel_ipsec_register, kernel_android_ipsec_create),
524 PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
525 PLUGIN_CALLBACK(charonservice_register, NULL),
526 PLUGIN_PROVIDE(CUSTOM, "android-backend"),
527 PLUGIN_DEPENDS(CUSTOM, "libcharon"),
528 };
529
530 INIT(this,
531 .public = {
532 .update_status = _update_status,
533 .update_imc_state = _update_imc_state,
534 .add_remediation_instr = _add_remediation_instr,
535 .bypass_socket = _bypass_socket,
536 .get_trusted_certificates = _get_trusted_certificates,
537 .get_user_certificate = _get_user_certificate,
538 .get_user_key = _get_user_key,
539 .get_vpnservice_builder = _get_vpnservice_builder,
540 .get_network_manager = _get_network_manager,
541 },
542 .attr = android_attr_create(),
543 .creds = android_creds_create(),
544 .builder = vpnservice_builder_create(builder),
545 .network_manager = network_manager_create(service),
546 .sockets = linked_list_create(),
547 .vpn_service = (*env)->NewGlobalRef(env, service),
548 );
549 charonservice = &this->public;
550
551 lib->plugins->add_static_features(lib->plugins, "androidbridge", features,
552 countof(features), TRUE, NULL, NULL);
553
554 #ifdef USE_BYOD
555 if (byod)
556 {
557 plugin_feature_t byod_features[] = {
558 PLUGIN_CALLBACK(imc_android_register, this->vpn_service),
559 PLUGIN_PROVIDE(CUSTOM, "android-imc"),
560 PLUGIN_DEPENDS(CUSTOM, "android-backend"),
561 PLUGIN_DEPENDS(CUSTOM, "imc-manager"),
562 };
563
564 lib->plugins->add_static_features(lib->plugins, "android-byod",
565 byod_features, countof(byod_features), TRUE, NULL, NULL);
566 }
567 #endif
568 }
569
570 /**
571 * Deinitialize the charonservice object
572 */
573 static void charonservice_deinit(JNIEnv *env)
574 {
575 private_charonservice_t *this = (private_charonservice_t*)charonservice;
576
577 this->network_manager->destroy(this->network_manager);
578 this->sockets->destroy(this->sockets);
579 this->builder->destroy(this->builder);
580 this->creds->destroy(this->creds);
581 this->attr->destroy(this->attr);
582 (*env)->DeleteGlobalRef(env, this->vpn_service);
583 free(this);
584 charonservice = NULL;
585 }
586
587 /**
588 * Handle SIGSEGV/SIGILL signals raised by threads
589 */
590 static void segv_handler(int signal)
591 {
592 dbg_android(DBG_DMN, 1, "thread %u received %d", thread_current_id(),
593 signal);
594 exit(1);
595 }
596
597 /**
598 * Initialize charon and the libraries via JNI
599 */
600 JNI_METHOD(CharonVpnService, initializeCharon, jboolean,
601 jobject builder, jstring jlogfile, jboolean byod)
602 {
603 struct sigaction action;
604 struct utsname utsname;
605 char *logfile, *plugins;
606
607 /* logging for library during initialization, as we have no bus yet */
608 dbg = dbg_android;
609
610 /* initialize library */
611 if (!library_init(NULL, "charon"))
612 {
613 library_deinit();
614 return FALSE;
615 }
616
617 /* set options before initializing other libraries that might read them */
618 logfile = androidjni_convert_jstring(env, jlogfile);
619 set_options(logfile);
620 free(logfile);
621
622 if (!libhydra_init())
623 {
624 libhydra_deinit();
625 library_deinit();
626 return FALSE;
627 }
628
629 if (!libipsec_init())
630 {
631 libipsec_deinit();
632 libhydra_deinit();
633 library_deinit();
634 return FALSE;
635 }
636
637 if (!libcharon_init())
638 {
639 libcharon_deinit();
640 libipsec_deinit();
641 libhydra_deinit();
642 library_deinit();
643 return FALSE;
644 }
645
646 charon->load_loggers(charon, NULL, FALSE);
647
648 charonservice_init(env, this, builder, byod);
649
650 if (uname(&utsname) != 0)
651 {
652 memset(&utsname, 0, sizeof(utsname));
653 }
654 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
655 utsname.sysname, utsname.release, utsname.machine);
656
657 #ifdef PLUGINS_BYOD
658 if (byod)
659 {
660 plugins = PLUGINS " " PLUGINS_BYOD;
661 }
662 else
663 #endif
664 {
665 plugins = PLUGINS;
666 }
667
668 if (!charon->initialize(charon, plugins))
669 {
670 libcharon_deinit();
671 charonservice_deinit(env);
672 libipsec_deinit();
673 libhydra_deinit();
674 library_deinit();
675 return FALSE;
676 }
677 lib->plugins->status(lib->plugins, LEVEL_CTRL);
678
679 /* add handler for SEGV and ILL etc. */
680 action.sa_handler = segv_handler;
681 action.sa_flags = 0;
682 sigemptyset(&action.sa_mask);
683 sigaction(SIGSEGV, &action, NULL);
684 sigaction(SIGILL, &action, NULL);
685 sigaction(SIGBUS, &action, NULL);
686 action.sa_handler = SIG_IGN;
687 sigaction(SIGPIPE, &action, NULL);
688
689 /* start daemon (i.e. the threads in the thread-pool) */
690 charon->start(charon);
691 return TRUE;
692 }
693
694 /**
695 * Deinitialize charon and all libraries
696 */
697 JNI_METHOD(CharonVpnService, deinitializeCharon, void)
698 {
699 /* deinitialize charon before we destroy our own objects */
700 libcharon_deinit();
701 charonservice_deinit(env);
702 libipsec_deinit();
703 libhydra_deinit();
704 library_deinit();
705 }
706
707 /**
708 * Initiate SA
709 */
710 JNI_METHOD(CharonVpnService, initiate, void,
711 jstring jconfig)
712 {
713 settings_t *settings;
714 char *config;
715
716 config = androidjni_convert_jstring(env, jconfig);
717 settings = settings_create_string(config);
718 initiate(settings);
719 }