98287ce31ae4d539f63c33259824fd1c7d6e3629
[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 this->creds->clear(this->creds);
410 DESTROY_IF(this->service);
411 this->service = android_service_create(this->creds, settings);
412 }
413
414 /**
415 * Initialize/deinitialize Android backend
416 */
417 static bool charonservice_register(plugin_t *plugin, plugin_feature_t *feature,
418 bool reg, void *data)
419 {
420 private_charonservice_t *this = (private_charonservice_t*)charonservice;
421 if (reg)
422 {
423 this->net_handler = android_net_create();
424 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
425 charon->attributes->add_handler(charon->attributes,
426 &this->attr->handler);
427 }
428 else
429 {
430 this->net_handler->destroy(this->net_handler);
431 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
432 charon->attributes->remove_handler(charon->attributes,
433 &this->attr->handler);
434 if (this->service)
435 {
436 this->service->destroy(this->service);
437 this->service = NULL;
438 }
439 }
440 return TRUE;
441 }
442
443 /**
444 * Set strongswan.conf options
445 */
446 static void set_options(char *logfile)
447 {
448 lib->settings->set_int(lib->settings,
449 "charon.plugins.android_log.loglevel", ANDROID_DEBUG_LEVEL);
450 /* setup file logger */
451 lib->settings->set_str(lib->settings,
452 "charon.filelog.%s.time_format", "%b %e %T", logfile);
453 lib->settings->set_bool(lib->settings,
454 "charon.filelog.%s.append", FALSE, logfile);
455 lib->settings->set_bool(lib->settings,
456 "charon.filelog.%s.flush_line", TRUE, logfile);
457 lib->settings->set_int(lib->settings,
458 "charon.filelog.%s.default", ANDROID_DEBUG_LEVEL, logfile);
459
460 lib->settings->set_int(lib->settings,
461 "charon.retransmit_tries", ANDROID_RETRASNMIT_TRIES);
462 lib->settings->set_double(lib->settings,
463 "charon.retransmit_timeout", ANDROID_RETRANSMIT_TIMEOUT);
464 lib->settings->set_double(lib->settings,
465 "charon.retransmit_base", ANDROID_RETRANSMIT_BASE);
466 lib->settings->set_int(lib->settings,
467 "charon.fragment_size", ANDROID_FRAGMENT_SIZE);
468 lib->settings->set_bool(lib->settings,
469 "charon.initiator_only", TRUE);
470 lib->settings->set_bool(lib->settings,
471 "charon.close_ike_on_child_failure", TRUE);
472 /* setting the source address breaks the VpnService.protect() function which
473 * uses SO_BINDTODEVICE internally. the addresses provided to the kernel as
474 * auxiliary data have precedence over this option causing a routing loop if
475 * the gateway is contained in the VPN routes. alternatively, providing an
476 * explicit device (in addition or instead of the source address) in the
477 * auxiliary data would also work, but we currently don't have that
478 * information */
479 lib->settings->set_bool(lib->settings,
480 "charon.plugins.socket-default.set_source", FALSE);
481 /* the Linux kernel does currently not support UDP encaspulation for IPv6
482 * so lets disable IPv6 for now to avoid issues with dual-stack gateways */
483 lib->settings->set_bool(lib->settings,
484 "charon.plugins.socket-default.use_ipv6", FALSE);
485 /* don't install virtual IPs via kernel-netlink */
486 lib->settings->set_bool(lib->settings,
487 "charon.install_virtual_ip", FALSE);
488 /* kernel-netlink should not trigger roam events, we use Android's
489 * ConnectivityManager for that, much less noise */
490 lib->settings->set_bool(lib->settings,
491 "charon.plugins.kernel-netlink.roam_events", FALSE);
492 /* ignore tun devices (it's mostly tun0 but it may already be taken, ignore
493 * some others too), also ignore lo as a default route points to it when
494 * no connectivity is available */
495 lib->settings->set_str(lib->settings,
496 "charon.interfaces_ignore", "lo, tun0, tun1, tun2, tun3, "
497 "tun4");
498
499 #ifdef USE_BYOD
500 lib->settings->set_str(lib->settings,
501 "charon.plugins.eap-tnc.protocol", "tnccs-2.0");
502 lib->settings->set_int(lib->settings,
503 "charon.plugins.eap-ttls.max_message_count", 0);
504 lib->settings->set_bool(lib->settings,
505 "android.imc.send_os_info", TRUE);
506 lib->settings->set_str(lib->settings,
507 "libtnccs.tnc_config", "");
508 #endif
509 }
510
511 /**
512 * Initialize the charonservice object
513 */
514 static void charonservice_init(JNIEnv *env, jobject service, jobject builder,
515 jboolean byod)
516 {
517 private_charonservice_t *this;
518 static plugin_feature_t features[] = {
519 PLUGIN_CALLBACK(kernel_ipsec_register, kernel_android_ipsec_create),
520 PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
521 PLUGIN_CALLBACK(charonservice_register, NULL),
522 PLUGIN_PROVIDE(CUSTOM, "android-backend"),
523 PLUGIN_DEPENDS(CUSTOM, "libcharon"),
524 };
525
526 INIT(this,
527 .public = {
528 .update_status = _update_status,
529 .update_imc_state = _update_imc_state,
530 .add_remediation_instr = _add_remediation_instr,
531 .bypass_socket = _bypass_socket,
532 .get_trusted_certificates = _get_trusted_certificates,
533 .get_user_certificate = _get_user_certificate,
534 .get_user_key = _get_user_key,
535 .get_vpnservice_builder = _get_vpnservice_builder,
536 .get_network_manager = _get_network_manager,
537 },
538 .attr = android_attr_create(),
539 .creds = android_creds_create(),
540 .builder = vpnservice_builder_create(builder),
541 .network_manager = network_manager_create(service),
542 .sockets = linked_list_create(),
543 .vpn_service = (*env)->NewGlobalRef(env, service),
544 );
545 charonservice = &this->public;
546
547 lib->plugins->add_static_features(lib->plugins, "androidbridge", features,
548 countof(features), TRUE, NULL, NULL);
549
550 #ifdef USE_BYOD
551 if (byod)
552 {
553 plugin_feature_t byod_features[] = {
554 PLUGIN_CALLBACK(imc_android_register, this->vpn_service),
555 PLUGIN_PROVIDE(CUSTOM, "android-imc"),
556 PLUGIN_DEPENDS(CUSTOM, "android-backend"),
557 PLUGIN_DEPENDS(CUSTOM, "imc-manager"),
558 };
559
560 lib->plugins->add_static_features(lib->plugins, "android-byod",
561 byod_features, countof(byod_features), TRUE, NULL, NULL);
562 }
563 #endif
564 }
565
566 /**
567 * Deinitialize the charonservice object
568 */
569 static void charonservice_deinit(JNIEnv *env)
570 {
571 private_charonservice_t *this = (private_charonservice_t*)charonservice;
572
573 this->network_manager->destroy(this->network_manager);
574 this->sockets->destroy(this->sockets);
575 this->builder->destroy(this->builder);
576 this->creds->destroy(this->creds);
577 this->attr->destroy(this->attr);
578 (*env)->DeleteGlobalRef(env, this->vpn_service);
579 free(this);
580 charonservice = NULL;
581 }
582
583 /**
584 * Handle SIGSEGV/SIGILL signals raised by threads
585 */
586 static void segv_handler(int signal)
587 {
588 dbg_android(DBG_DMN, 1, "thread %u received %d", thread_current_id(),
589 signal);
590 exit(1);
591 }
592
593 /**
594 * Initialize charon and the libraries via JNI
595 */
596 JNI_METHOD(CharonVpnService, initializeCharon, jboolean,
597 jobject builder, jstring jlogfile, jboolean byod)
598 {
599 struct sigaction action;
600 struct utsname utsname;
601 char *logfile, *plugins;
602
603 /* logging for library during initialization, as we have no bus yet */
604 dbg = dbg_android;
605
606 /* initialize library */
607 if (!library_init(NULL, "charon"))
608 {
609 library_deinit();
610 return FALSE;
611 }
612
613 /* set options before initializing other libraries that might read them */
614 logfile = androidjni_convert_jstring(env, jlogfile);
615 set_options(logfile);
616 free(logfile);
617
618 if (!libhydra_init())
619 {
620 libhydra_deinit();
621 library_deinit();
622 return FALSE;
623 }
624
625 if (!libipsec_init())
626 {
627 libipsec_deinit();
628 libhydra_deinit();
629 library_deinit();
630 return FALSE;
631 }
632
633 if (!libcharon_init())
634 {
635 libcharon_deinit();
636 libipsec_deinit();
637 libhydra_deinit();
638 library_deinit();
639 return FALSE;
640 }
641
642 charon->load_loggers(charon, NULL, FALSE);
643
644 charonservice_init(env, this, builder, byod);
645
646 if (uname(&utsname) != 0)
647 {
648 memset(&utsname, 0, sizeof(utsname));
649 }
650 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
651 utsname.sysname, utsname.release, utsname.machine);
652
653 #ifdef PLUGINS_BYOD
654 if (byod)
655 {
656 plugins = PLUGINS " " PLUGINS_BYOD;
657 }
658 else
659 #endif
660 {
661 plugins = PLUGINS;
662 }
663
664 if (!charon->initialize(charon, plugins))
665 {
666 libcharon_deinit();
667 charonservice_deinit(env);
668 libipsec_deinit();
669 libhydra_deinit();
670 library_deinit();
671 return FALSE;
672 }
673 lib->plugins->status(lib->plugins, LEVEL_CTRL);
674
675 /* add handler for SEGV and ILL etc. */
676 action.sa_handler = segv_handler;
677 action.sa_flags = 0;
678 sigemptyset(&action.sa_mask);
679 sigaction(SIGSEGV, &action, NULL);
680 sigaction(SIGILL, &action, NULL);
681 sigaction(SIGBUS, &action, NULL);
682 action.sa_handler = SIG_IGN;
683 sigaction(SIGPIPE, &action, NULL);
684
685 /* start daemon (i.e. the threads in the thread-pool) */
686 charon->start(charon);
687 return TRUE;
688 }
689
690 /**
691 * Deinitialize charon and all libraries
692 */
693 JNI_METHOD(CharonVpnService, deinitializeCharon, void)
694 {
695 /* deinitialize charon before we destroy our own objects */
696 libcharon_deinit();
697 charonservice_deinit(env);
698 libipsec_deinit();
699 libhydra_deinit();
700 library_deinit();
701 }
702
703 /**
704 * Initiate SA
705 */
706 JNI_METHOD(CharonVpnService, initiate, void,
707 jstring jconfig)
708 {
709 settings_t *settings;
710 char *config;
711
712 config = androidjni_convert_jstring(env, jconfig);
713 settings = settings_create_string(config);
714 initiate(settings);
715 }