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