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