stroke: Use chunk_map() instead of non-portable mmap()
[strongswan.git] / src / libcharon / plugins / stroke / stroke_cred.c
1 /*
2 * Copyright (C) 2008-2013 Tobias Brunner
3 * Copyright (C) 2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <limits.h>
20 #include <libgen.h>
21 #include <fcntl.h>
22 #include <errno.h>
23 #include <unistd.h>
24
25 #ifdef HAVE_GLOB_H
26 #include <glob.h>
27 #endif
28
29 #include "stroke_cred.h"
30
31 #include <credentials/certificates/x509.h>
32 #include <credentials/certificates/crl.h>
33 #include <credentials/certificates/ac.h>
34 #include <credentials/containers/pkcs12.h>
35 #include <credentials/sets/mem_cred.h>
36 #include <credentials/sets/callback_cred.h>
37 #include <collections/linked_list.h>
38 #include <utils/lexparser.h>
39 #include <threading/rwlock.h>
40 #include <daemon.h>
41
42 /* configuration directories and files */
43 #define CONFIG_DIR IPSEC_CONFDIR
44 #define IPSEC_D_DIR CONFIG_DIR "/ipsec.d"
45 #define PRIVATE_KEY_DIR IPSEC_D_DIR "/private"
46 #define CERTIFICATE_DIR IPSEC_D_DIR "/certs"
47 #define CA_CERTIFICATE_DIR IPSEC_D_DIR "/cacerts"
48 #define AA_CERTIFICATE_DIR IPSEC_D_DIR "/aacerts"
49 #define ATTR_CERTIFICATE_DIR IPSEC_D_DIR "/acerts"
50 #define OCSP_CERTIFICATE_DIR IPSEC_D_DIR "/ocspcerts"
51 #define CRL_DIR IPSEC_D_DIR "/crls"
52 #define SECRETS_FILE CONFIG_DIR "/ipsec.secrets"
53
54 #define MAX_SECRETS_RECURSION 10
55
56 typedef struct private_stroke_cred_t private_stroke_cred_t;
57
58 /**
59 * private data of stroke_cred
60 */
61 struct private_stroke_cred_t {
62
63 /**
64 * public functions
65 */
66 stroke_cred_t public;
67
68 /**
69 * credentials
70 */
71 mem_cred_t *creds;
72
73 /**
74 * ignore missing CA basic constraint (i.e. treat all certificates in
75 * ipsec.conf ca sections and ipsec.d/cacerts as CA certificates)
76 */
77 bool force_ca_cert;
78
79 /**
80 * cache CRLs to disk?
81 */
82 bool cachecrl;
83 };
84
85 /** Length of smartcard specifier parts (module, keyid) */
86 #define SC_PART_LEN 128
87
88 /**
89 * Kind of smartcard specifier token
90 */
91 typedef enum {
92 SC_FORMAT_SLOT_MODULE_KEYID,
93 SC_FORMAT_SLOT_KEYID,
94 SC_FORMAT_KEYID,
95 SC_FORMAT_INVALID,
96 } smartcard_format_t;
97
98 /**
99 * Parse a smartcard specifier token
100 */
101 static smartcard_format_t parse_smartcard(char *smartcard, u_int *slot,
102 char *module, char *keyid)
103 {
104 /* The token has one of the following three formats:
105 * - %smartcard<slot>@<module>:<keyid>
106 * - %smartcard<slot>:<keyid>
107 * - %smartcard:<keyid>
108 */
109 char buf[2 * SC_PART_LEN], *pos;
110
111 if (sscanf(smartcard, "%%smartcard%u@%255s", slot, buf) == 2)
112 {
113 pos = strchr(buf, ':');
114 if (!pos)
115 {
116 return SC_FORMAT_INVALID;
117 }
118 *pos++ = '\0';
119 snprintf(module, SC_PART_LEN, "%s", buf);
120 snprintf(keyid, SC_PART_LEN, "%s", pos);
121 return SC_FORMAT_SLOT_MODULE_KEYID;
122 }
123 if (sscanf(smartcard, "%%smartcard%u:%127s", slot, keyid) == 2)
124 {
125 return SC_FORMAT_SLOT_KEYID;
126 }
127 if (sscanf(smartcard, "%%smartcard:%127s", keyid) == 1)
128 {
129 return SC_FORMAT_KEYID;
130 }
131 return SC_FORMAT_INVALID;
132 }
133
134 /**
135 * Load a credential from a smartcard
136 */
137 static certificate_t *load_from_smartcard(smartcard_format_t format,
138 u_int slot, char *module, char *keyid,
139 credential_type_t type, int subtype)
140 {
141 chunk_t chunk;
142 void *cred;
143
144 chunk = chunk_from_hex(chunk_create(keyid, strlen(keyid)), NULL);
145 switch (format)
146 {
147 case SC_FORMAT_SLOT_MODULE_KEYID:
148 cred = lib->creds->create(lib->creds, type, subtype,
149 BUILD_PKCS11_SLOT, slot,
150 BUILD_PKCS11_MODULE, module,
151 BUILD_PKCS11_KEYID, chunk, BUILD_END);
152 break;
153 case SC_FORMAT_SLOT_KEYID:
154 cred = lib->creds->create(lib->creds, type, subtype,
155 BUILD_PKCS11_SLOT, slot,
156 BUILD_PKCS11_KEYID, chunk, BUILD_END);
157 break;
158 case SC_FORMAT_KEYID:
159 cred = lib->creds->create(lib->creds, type, subtype,
160 BUILD_PKCS11_KEYID, chunk, BUILD_END);
161 break;
162 default:
163 cred = NULL;
164 break;
165 }
166 free(chunk.ptr);
167
168 return cred;
169 }
170
171 METHOD(stroke_cred_t, load_ca, certificate_t*,
172 private_stroke_cred_t *this, char *filename)
173 {
174 certificate_t *cert = NULL;
175 char path[PATH_MAX];
176
177 if (strpfx(filename, "%smartcard"))
178 {
179 smartcard_format_t format;
180 char module[SC_PART_LEN], keyid[SC_PART_LEN];
181 u_int slot;
182
183 format = parse_smartcard(filename, &slot, module, keyid);
184 if (format != SC_FORMAT_INVALID)
185 {
186 cert = (certificate_t*)load_from_smartcard(format,
187 slot, module, keyid, CRED_CERTIFICATE, CERT_X509);
188 }
189 }
190 else
191 {
192 if (*filename == '/')
193 {
194 snprintf(path, sizeof(path), "%s", filename);
195 }
196 else
197 {
198 snprintf(path, sizeof(path), "%s/%s", CA_CERTIFICATE_DIR, filename);
199 }
200
201 if (this->force_ca_cert)
202 { /* we treat this certificate as a CA certificate even if it has no
203 * CA basic constraint */
204 cert = lib->creds->create(lib->creds,
205 CRED_CERTIFICATE, CERT_X509,
206 BUILD_FROM_FILE, path, BUILD_X509_FLAG, X509_CA,
207 BUILD_END);
208 }
209 else
210 {
211 cert = lib->creds->create(lib->creds,
212 CRED_CERTIFICATE, CERT_X509,
213 BUILD_FROM_FILE, path,
214 BUILD_END);
215 }
216 }
217 if (cert)
218 {
219 x509_t *x509 = (x509_t*)cert;
220
221 if (!(x509->get_flags(x509) & X509_CA))
222 {
223 DBG1(DBG_CFG, " ca certificate \"%Y\" misses ca basic constraint, "
224 "discarded", cert->get_subject(cert));
225 cert->destroy(cert);
226 return NULL;
227 }
228 DBG1(DBG_CFG, " loaded ca certificate \"%Y\" from '%s'",
229 cert->get_subject(cert), filename);
230 return this->creds->add_cert_ref(this->creds, TRUE, cert);
231 }
232 return NULL;
233 }
234
235 METHOD(stroke_cred_t, load_peer, certificate_t*,
236 private_stroke_cred_t *this, char *filename)
237 {
238 certificate_t *cert = NULL;
239 char path[PATH_MAX];
240
241 if (strpfx(filename, "%smartcard"))
242 {
243 smartcard_format_t format;
244 char module[SC_PART_LEN], keyid[SC_PART_LEN];
245 u_int slot;
246
247 format = parse_smartcard(filename, &slot, module, keyid);
248 if (format != SC_FORMAT_INVALID)
249 {
250 cert = (certificate_t*)load_from_smartcard(format,
251 slot, module, keyid, CRED_CERTIFICATE, CERT_X509);
252 }
253 }
254 else
255 {
256 if (*filename == '/')
257 {
258 snprintf(path, sizeof(path), "%s", filename);
259 }
260 else
261 {
262 snprintf(path, sizeof(path), "%s/%s", CERTIFICATE_DIR, filename);
263 }
264
265 cert = lib->creds->create(lib->creds,
266 CRED_CERTIFICATE, CERT_ANY,
267 BUILD_FROM_FILE, path,
268 BUILD_END);
269 }
270 if (cert)
271 {
272 cert = this->creds->add_cert_ref(this->creds, TRUE, cert);
273 DBG1(DBG_CFG, " loaded certificate \"%Y\" from '%s'",
274 cert->get_subject(cert), filename);
275 return cert;
276 }
277 DBG1(DBG_CFG, " loading certificate from '%s' failed", filename);
278 return NULL;
279 }
280
281 METHOD(stroke_cred_t, load_pubkey, certificate_t*,
282 private_stroke_cred_t *this, char *filename, identification_t *identity)
283 {
284 certificate_t *cert;
285 public_key_t *key;
286 char path[PATH_MAX];
287 builder_part_t build_part;
288 key_type_t type = KEY_ANY;
289
290 if (streq(filename, "%dns"))
291 {
292 return NULL;
293 }
294 if (strncaseeq(filename, "dns:", 4))
295 { /* RFC 3110 format */
296 build_part = BUILD_BLOB_DNSKEY;
297 /* not a complete RR, only RSA supported */
298 type = KEY_RSA;
299 filename += 4;
300 }
301 else if (strncaseeq(filename, "ssh:", 4))
302 { /* SSH key */
303 build_part = BUILD_BLOB_SSHKEY;
304 filename += 4;
305 }
306 else
307 { /* try PKCS#1 by default */
308 build_part = BUILD_BLOB_ASN1_DER;
309 }
310 if (strncaseeq(filename, "0x", 2) || strncaseeq(filename, "0s", 2))
311 {
312 chunk_t printable_key, raw_key;
313
314 printable_key = chunk_create(filename + 2, strlen(filename) - 2);
315 raw_key = strncaseeq(filename, "0x", 2) ?
316 chunk_from_hex(printable_key, NULL) :
317 chunk_from_base64(printable_key, NULL);
318 key = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, type,
319 build_part, raw_key, BUILD_END);
320 chunk_free(&raw_key);
321 if (key)
322 {
323 cert = lib->creds->create(lib->creds, CRED_CERTIFICATE,
324 CERT_TRUSTED_PUBKEY,
325 BUILD_PUBLIC_KEY, key,
326 BUILD_SUBJECT, identity,
327 BUILD_END);
328 type = key->get_type(key);
329 key->destroy(key);
330 if (cert)
331 {
332 cert = this->creds->add_cert_ref(this->creds, TRUE, cert);
333 DBG1(DBG_CFG, " loaded %N public key for \"%Y\"",
334 key_type_names, type, identity);
335 return cert;
336 }
337 }
338 DBG1(DBG_CFG, " loading public key for \"%Y\" failed", identity);
339 }
340 else
341 {
342 if (*filename == '/')
343 {
344 snprintf(path, sizeof(path), "%s", filename);
345 }
346 else
347 {
348 snprintf(path, sizeof(path), "%s/%s", CERTIFICATE_DIR, filename);
349 }
350
351 cert = lib->creds->create(lib->creds,
352 CRED_CERTIFICATE, CERT_TRUSTED_PUBKEY,
353 BUILD_FROM_FILE, path,
354 BUILD_SUBJECT, identity,
355 BUILD_END);
356 if (cert)
357 {
358 cert = this->creds->add_cert_ref(this->creds, TRUE, cert);
359 key = cert->get_public_key(cert);
360 type = key->get_type(key);
361 key->destroy(key);
362 DBG1(DBG_CFG, " loaded %N public key for \"%Y\" from '%s'",
363 key_type_names, type, identity, filename);
364 return cert;
365 }
366 DBG1(DBG_CFG, " loading public key for \"%Y\" from '%s' failed",
367 identity, filename);
368 }
369 return NULL;
370 }
371
372 /**
373 * load trusted certificates from a directory
374 */
375 static void load_certdir(private_stroke_cred_t *this, char *path,
376 certificate_type_t type, x509_flag_t flag)
377 {
378 struct stat st;
379 char *file;
380
381 enumerator_t *enumerator = enumerator_create_directory(path);
382
383 if (!enumerator)
384 {
385 DBG1(DBG_CFG, " reading directory failed");
386 return;
387 }
388
389 while (enumerator->enumerate(enumerator, NULL, &file, &st))
390 {
391 certificate_t *cert;
392
393 if (!S_ISREG(st.st_mode))
394 {
395 /* skip special file */
396 continue;
397 }
398 switch (type)
399 {
400 case CERT_X509:
401 if (flag & X509_CA)
402 {
403 if (this->force_ca_cert)
404 { /* treat this certificate as CA cert even it has no
405 * CA basic constraint */
406 cert = lib->creds->create(lib->creds,
407 CRED_CERTIFICATE, CERT_X509,
408 BUILD_FROM_FILE, file, BUILD_X509_FLAG,
409 X509_CA, BUILD_END);
410 }
411 else
412 {
413 cert = lib->creds->create(lib->creds,
414 CRED_CERTIFICATE, CERT_X509,
415 BUILD_FROM_FILE, file, BUILD_END);
416 }
417 if (cert)
418 {
419 x509_t *x509 = (x509_t*)cert;
420
421 if (!(x509->get_flags(x509) & X509_CA))
422 {
423 DBG1(DBG_CFG, " ca certificate \"%Y\" lacks "
424 "ca basic constraint, discarded",
425 cert->get_subject(cert));
426 cert->destroy(cert);
427 cert = NULL;
428 }
429 else
430 {
431 DBG1(DBG_CFG, " loaded ca certificate \"%Y\" "
432 "from '%s'", cert->get_subject(cert), file);
433 }
434 }
435 else
436 {
437 DBG1(DBG_CFG, " loading ca certificate from '%s' "
438 "failed", file);
439 }
440 }
441 else
442 { /* for all other flags, we add them to the certificate. */
443 cert = lib->creds->create(lib->creds,
444 CRED_CERTIFICATE, CERT_X509,
445 BUILD_FROM_FILE, file,
446 BUILD_X509_FLAG, flag, BUILD_END);
447 if (cert)
448 {
449 DBG1(DBG_CFG, " loaded certificate \"%Y\" from '%s'",
450 cert->get_subject(cert), file);
451 }
452 else
453 {
454 DBG1(DBG_CFG, " loading certificate from '%s' "
455 "failed", file);
456 }
457 }
458 if (cert)
459 {
460 this->creds->add_cert(this->creds, TRUE, cert);
461 }
462 break;
463 case CERT_X509_CRL:
464 cert = lib->creds->create(lib->creds,
465 CRED_CERTIFICATE, CERT_X509_CRL,
466 BUILD_FROM_FILE, file,
467 BUILD_END);
468 if (cert)
469 {
470 this->creds->add_crl(this->creds, (crl_t*)cert);
471 DBG1(DBG_CFG, " loaded crl from '%s'", file);
472 }
473 else
474 {
475 DBG1(DBG_CFG, " loading crl from '%s' failed", file);
476 }
477 break;
478 case CERT_X509_AC:
479 cert = lib->creds->create(lib->creds,
480 CRED_CERTIFICATE, CERT_X509_AC,
481 BUILD_FROM_FILE, file,
482 BUILD_END);
483 if (cert)
484 {
485 this->creds->add_cert(this->creds, FALSE, cert);
486 DBG1(DBG_CFG, " loaded attribute certificate from '%s'",
487 file);
488 }
489 else
490 {
491 DBG1(DBG_CFG, " loading attribute certificate from '%s' "
492 "failed", file);
493 }
494 break;
495 default:
496 break;
497 }
498 }
499 enumerator->destroy(enumerator);
500 }
501
502 METHOD(stroke_cred_t, cache_cert, void,
503 private_stroke_cred_t *this, certificate_t *cert)
504 {
505 if (cert->get_type(cert) == CERT_X509_CRL && this->cachecrl)
506 {
507 /* CRLs get written to /etc/ipsec.d/crls/<authkeyId>.crl */
508 crl_t *crl = (crl_t*)cert;
509
510 cert->get_ref(cert);
511 if (this->creds->add_crl(this->creds, crl))
512 {
513 char buf[BUF_LEN];
514 chunk_t chunk, hex;
515
516 chunk = crl->get_authKeyIdentifier(crl);
517 hex = chunk_to_hex(chunk, NULL, FALSE);
518 snprintf(buf, sizeof(buf), "%s/%s.crl", CRL_DIR, hex.ptr);
519 free(hex.ptr);
520
521 if (cert->get_encoding(cert, CERT_ASN1_DER, &chunk))
522 {
523 if (chunk_write(chunk, buf, 022, TRUE))
524 {
525 DBG1(DBG_CFG, " written crl file '%s' (%d bytes)",
526 buf, chunk.len);
527 }
528 else
529 {
530 DBG1(DBG_CFG, " writing crl file '%s' failed: %s",
531 buf, strerror(errno));
532 }
533 free(chunk.ptr);
534 }
535 }
536 }
537 }
538
539 METHOD(stroke_cred_t, cachecrl, void,
540 private_stroke_cred_t *this, bool enabled)
541 {
542 DBG1(DBG_CFG, "crl caching to %s %s",
543 CRL_DIR, enabled ? "enabled" : "disabled");
544 this->cachecrl = enabled;
545 }
546
547
548 /**
549 * Convert a string of characters into a binary secret
550 * A string between single or double quotes is treated as ASCII characters
551 * A string prepended by 0x is treated as HEX and prepended by 0s as Base64
552 */
553 static err_t extract_secret(chunk_t *secret, chunk_t *line)
554 {
555 chunk_t raw_secret;
556 char delimiter = ' ';
557 bool quotes = FALSE;
558
559 if (!eat_whitespace(line))
560 {
561 return "missing secret";
562 }
563
564 if (*line->ptr == '\'' || *line->ptr == '"')
565 {
566 quotes = TRUE;
567 delimiter = *line->ptr;
568 line->ptr++; line->len--;
569 }
570
571 if (!extract_token(&raw_secret, delimiter, line))
572 {
573 if (delimiter == ' ')
574 {
575 raw_secret = *line;
576 }
577 else
578 {
579 return "missing second delimiter";
580 }
581 }
582
583 if (quotes)
584 {
585 /* treat as an ASCII string */
586 *secret = chunk_clone(raw_secret);
587 return NULL;
588 }
589 /* treat 0x as hex, 0s as base64 */
590 if (raw_secret.len > 2)
591 {
592 if (strncasecmp("0x", raw_secret.ptr, 2) == 0)
593 {
594 *secret = chunk_from_hex(chunk_skip(raw_secret, 2), NULL);
595 return NULL;
596 }
597 if (strncasecmp("0s", raw_secret.ptr, 2) == 0)
598 {
599 *secret = chunk_from_base64(chunk_skip(raw_secret, 2), NULL);
600 return NULL;
601 }
602 }
603 *secret = chunk_clone(raw_secret);
604 return NULL;
605 }
606
607 /**
608 * Data for passphrase callback
609 */
610 typedef struct {
611 /** cached passphrases */
612 mem_cred_t *cache;
613 /** socket we use for prompting */
614 FILE *prompt;
615 /** type of secret to unlock */
616 int type;
617 /** private key file */
618 char *path;
619 /** number of tries */
620 int try;
621 } passphrase_cb_data_t;
622
623 /**
624 * Callback function to receive passphrases
625 */
626 static shared_key_t* passphrase_cb(passphrase_cb_data_t *data,
627 shared_key_type_t type, identification_t *me,
628 identification_t *other, id_match_t *match_me,
629 id_match_t *match_other)
630 {
631 static const int max_tries = 3;
632 shared_key_t *shared;
633 chunk_t secret;
634 char buf[256];
635
636 if (type != SHARED_ANY && type != SHARED_PRIVATE_KEY_PASS)
637 {
638 return NULL;
639 }
640
641 data->try++;
642 if (data->try > max_tries + 1)
643 { /* another builder might call this after we gave up, fail silently */
644 return NULL;
645 }
646 if (data->try > max_tries)
647 {
648 fprintf(data->prompt, "Passphrase invalid, giving up.\n");
649 return NULL;
650 }
651 if (data->try > 1)
652 {
653 fprintf(data->prompt, "Passphrase invalid!\n");
654 }
655 fprintf(data->prompt, "%s '%s' is encrypted.\n",
656 data->type == CRED_PRIVATE_KEY ? "Private key" : "PKCS#12 file",
657 data->path);
658 fprintf(data->prompt, "Passphrase:\n");
659 if (fgets(buf, sizeof(buf), data->prompt))
660 {
661 secret = chunk_create(buf, strlen(buf));
662 if (secret.len > 1)
663 { /* trim appended \n */
664 secret.len--;
665 if (match_me)
666 {
667 *match_me = ID_MATCH_PERFECT;
668 }
669 if (match_other)
670 {
671 *match_other = ID_MATCH_NONE;
672 }
673 shared = shared_key_create(SHARED_PRIVATE_KEY_PASS,
674 chunk_clone(secret));
675 data->cache->add_shared(data->cache, shared->get_ref(shared), NULL);
676 return shared;
677 }
678 }
679 return NULL;
680 }
681
682 /**
683 * Data for PIN callback
684 */
685 typedef struct {
686 /** socket we use for prompting */
687 FILE *prompt;
688 /** card label */
689 char *card;
690 /** card keyid */
691 chunk_t keyid;
692 /** number of tries */
693 int try;
694 } pin_cb_data_t;
695
696 /**
697 * Callback function to receive PINs
698 */
699 static shared_key_t* pin_cb(pin_cb_data_t *data, shared_key_type_t type,
700 identification_t *me, identification_t *other,
701 id_match_t *match_me, id_match_t *match_other)
702 {
703 chunk_t secret;
704 char buf[256];
705
706 if (type != SHARED_ANY && type != SHARED_PIN)
707 {
708 return NULL;
709 }
710
711 if (!me || !chunk_equals(me->get_encoding(me), data->keyid))
712 {
713 return NULL;
714 }
715
716 data->try++;
717 if (data->try > 1)
718 {
719 fprintf(data->prompt, "PIN invalid, aborting.\n");
720 return NULL;
721 }
722 fprintf(data->prompt, "Login to '%s' required\n", data->card);
723 fprintf(data->prompt, "PIN:\n");
724 if (fgets(buf, sizeof(buf), data->prompt))
725 {
726 secret = chunk_create(buf, strlen(buf));
727 if (secret.len > 1)
728 { /* trim appended \n */
729 secret.len--;
730 if (match_me)
731 {
732 *match_me = ID_MATCH_PERFECT;
733 }
734 if (match_other)
735 {
736 *match_other = ID_MATCH_NONE;
737 }
738 return shared_key_create(SHARED_PIN, chunk_clone(secret));
739 }
740 }
741 return NULL;
742 }
743
744 /**
745 * Load a smartcard with a PIN
746 */
747 static bool load_pin(mem_cred_t *secrets, chunk_t line, int line_nr,
748 FILE *prompt)
749 {
750 chunk_t sc = chunk_empty, secret = chunk_empty;
751 char smartcard[BUF_LEN], keyid[SC_PART_LEN], module[SC_PART_LEN];
752 private_key_t *key = NULL;
753 u_int slot;
754 chunk_t chunk;
755 shared_key_t *shared;
756 identification_t *id;
757 mem_cred_t *mem = NULL;
758 callback_cred_t *cb = NULL;
759 pin_cb_data_t pin_data;
760 smartcard_format_t format;
761
762 err_t ugh = extract_value(&sc, &line);
763
764 if (ugh != NULL)
765 {
766 DBG1(DBG_CFG, "line %d: %s", line_nr, ugh);
767 return FALSE;
768 }
769 if (sc.len == 0)
770 {
771 DBG1(DBG_CFG, "line %d: expected %%smartcard specifier", line_nr);
772 return FALSE;
773 }
774 snprintf(smartcard, sizeof(smartcard), "%.*s", (int)sc.len, sc.ptr);
775 smartcard[sizeof(smartcard) - 1] = '\0';
776
777 format = parse_smartcard(smartcard, &slot, module, keyid);
778 if (format == SC_FORMAT_INVALID)
779 {
780 DBG1(DBG_CFG, "line %d: the given %%smartcard specifier is not"
781 " supported or invalid", line_nr);
782 return FALSE;
783 }
784
785 if (!eat_whitespace(&line))
786 {
787 DBG1(DBG_CFG, "line %d: expected PIN", line_nr);
788 return FALSE;
789 }
790 ugh = extract_secret(&secret, &line);
791 if (ugh != NULL)
792 {
793 DBG1(DBG_CFG, "line %d: malformed PIN: %s", line_nr, ugh);
794 return FALSE;
795 }
796
797 chunk = chunk_from_hex(chunk_create(keyid, strlen(keyid)), NULL);
798 if (secret.len == 7 && strpfx(secret.ptr, "%prompt"))
799 {
800 free(secret.ptr);
801 if (!prompt)
802 { /* no IO channel to prompt, skip */
803 chunk_clear(&chunk);
804 return TRUE;
805 }
806 /* use callback credential set to prompt for the pin */
807 pin_data.prompt = prompt;
808 pin_data.card = smartcard;
809 pin_data.keyid = chunk;
810 pin_data.try = 0;
811 cb = callback_cred_create_shared((void*)pin_cb, &pin_data);
812 lib->credmgr->add_local_set(lib->credmgr, &cb->set, FALSE);
813 }
814 else
815 {
816 /* provide our pin in a temporary credential set */
817 shared = shared_key_create(SHARED_PIN, secret);
818 id = identification_create_from_encoding(ID_KEY_ID, chunk);
819 mem = mem_cred_create();
820 mem->add_shared(mem, shared, id, NULL);
821 lib->credmgr->add_local_set(lib->credmgr, &mem->set, FALSE);
822 }
823
824 /* unlock: smartcard needs the pin and potentially calls public set */
825 key = (private_key_t*)load_from_smartcard(format, slot, module, keyid,
826 CRED_PRIVATE_KEY, KEY_ANY);
827 if (mem)
828 {
829 lib->credmgr->remove_local_set(lib->credmgr, &mem->set);
830 mem->destroy(mem);
831 }
832 if (cb)
833 {
834 lib->credmgr->remove_local_set(lib->credmgr, &cb->set);
835 cb->destroy(cb);
836 }
837 chunk_clear(&chunk);
838
839 if (key)
840 {
841 DBG1(DBG_CFG, " loaded private key from %.*s", (int)sc.len, sc.ptr);
842 secrets->add_key(secrets, key);
843 }
844 return TRUE;
845 }
846
847 /**
848 * Load a private key or PKCS#12 container from a file
849 */
850 static bool load_from_file(chunk_t line, int line_nr, FILE *prompt,
851 char *path, int type, int subtype,
852 void **result)
853 {
854 chunk_t filename;
855 chunk_t secret = chunk_empty;
856
857 err_t ugh = extract_value(&filename, &line);
858
859 if (ugh != NULL)
860 {
861 DBG1(DBG_CFG, "line %d: %s", line_nr, ugh);
862 return FALSE;
863 }
864 if (filename.len == 0)
865 {
866 DBG1(DBG_CFG, "line %d: empty filename", line_nr);
867 return FALSE;
868 }
869 if (*filename.ptr == '/')
870 {
871 /* absolute path name */
872 snprintf(path, PATH_MAX, "%.*s", (int)filename.len, filename.ptr);
873 }
874 else
875 {
876 /* relative path name */
877 snprintf(path, PATH_MAX, "%s/%.*s", PRIVATE_KEY_DIR,
878 (int)filename.len, filename.ptr);
879 }
880
881 /* check for optional passphrase */
882 if (eat_whitespace(&line))
883 {
884 ugh = extract_secret(&secret, &line);
885 if (ugh != NULL)
886 {
887 DBG1(DBG_CFG, "line %d: malformed passphrase: %s", line_nr, ugh);
888 return FALSE;
889 }
890 }
891 if (secret.len == 7 && strpfx(secret.ptr, "%prompt"))
892 {
893 callback_cred_t *cb;
894 passphrase_cb_data_t pp_data = {
895 .prompt = prompt,
896 .type = type,
897 .path = path,
898 .try = 0,
899 };
900
901 free(secret.ptr);
902 if (!prompt)
903 {
904 *result = NULL;
905 return TRUE;
906 }
907 /* add cache first so if valid passphrases are needed multiple times
908 * the callback is not called anymore */
909 pp_data.cache = mem_cred_create();
910 lib->credmgr->add_local_set(lib->credmgr, &pp_data.cache->set, FALSE);
911 /* use callback credential set to prompt for the passphrase */
912 cb = callback_cred_create_shared((void*)passphrase_cb, &pp_data);
913 lib->credmgr->add_local_set(lib->credmgr, &cb->set, FALSE);
914
915 *result = lib->creds->create(lib->creds, type, subtype,
916 BUILD_FROM_FILE, path, BUILD_END);
917
918 lib->credmgr->remove_local_set(lib->credmgr, &cb->set);
919 cb->destroy(cb);
920 lib->credmgr->remove_local_set(lib->credmgr, &pp_data.cache->set);
921 pp_data.cache->destroy(pp_data.cache);
922 }
923 else
924 {
925 mem_cred_t *mem = NULL;
926 shared_key_t *shared;
927
928 /* provide our pin in a temporary credential set */
929 shared = shared_key_create(SHARED_PRIVATE_KEY_PASS, secret);
930 mem = mem_cred_create();
931 mem->add_shared(mem, shared, NULL);
932 if (eat_whitespace(&line))
933 { /* if there is a second passphrase add that too, could be needed for
934 * PKCS#12 files using different passwords for MAC and encryption */
935 ugh = extract_secret(&secret, &line);
936 if (ugh != NULL)
937 {
938 DBG1(DBG_CFG, "line %d: malformed passphrase: %s", line_nr, ugh);
939 mem->destroy(mem);
940 return FALSE;
941 }
942 shared = shared_key_create(SHARED_PRIVATE_KEY_PASS, secret);
943 mem->add_shared(mem, shared, NULL);
944 }
945 lib->credmgr->add_local_set(lib->credmgr, &mem->set, FALSE);
946
947 *result = lib->creds->create(lib->creds, type, subtype,
948 BUILD_FROM_FILE, path, BUILD_END);
949
950 lib->credmgr->remove_local_set(lib->credmgr, &mem->set);
951 mem->destroy(mem);
952 }
953 return TRUE;
954 }
955
956 /**
957 * Load a private key
958 */
959 static bool load_private(mem_cred_t *secrets, chunk_t line, int line_nr,
960 FILE *prompt, key_type_t key_type)
961 {
962 char path[PATH_MAX];
963 private_key_t *key;
964
965 if (!load_from_file(line, line_nr, prompt, path, CRED_PRIVATE_KEY,
966 key_type, (void**)&key))
967 {
968 return FALSE;
969 }
970 if (key)
971 {
972 DBG1(DBG_CFG, " loaded %N private key from '%s'",
973 key_type_names, key->get_type(key), path);
974 secrets->add_key(secrets, key);
975 }
976 else
977 {
978 DBG1(DBG_CFG, " loading private key from '%s' failed", path);
979 }
980 return TRUE;
981 }
982
983 /**
984 * Load a PKCS#12 container
985 */
986 static bool load_pkcs12(private_stroke_cred_t *this, mem_cred_t *secrets,
987 chunk_t line, int line_nr, FILE *prompt)
988 {
989 enumerator_t *enumerator;
990 char path[PATH_MAX];
991 certificate_t *cert;
992 private_key_t *key;
993 pkcs12_t *pkcs12;
994
995 if (!load_from_file(line, line_nr, prompt, path, CRED_CONTAINER,
996 CONTAINER_PKCS12, (void**)&pkcs12))
997 {
998 return FALSE;
999 }
1000 if (!pkcs12)
1001 {
1002 DBG1(DBG_CFG, " loading credentials from '%s' failed", path);
1003 return TRUE;
1004 }
1005 enumerator = pkcs12->create_cert_enumerator(pkcs12);
1006 while (enumerator->enumerate(enumerator, &cert))
1007 {
1008 x509_t *x509 = (x509_t*)cert;
1009
1010 if (x509->get_flags(x509) & X509_CA)
1011 {
1012 DBG1(DBG_CFG, " loaded ca certificate \"%Y\" from '%s'",
1013 cert->get_subject(cert), path);
1014 }
1015 else
1016 {
1017 DBG1(DBG_CFG, " loaded certificate \"%Y\" from '%s'",
1018 cert->get_subject(cert), path);
1019 }
1020 this->creds->add_cert(this->creds, TRUE, cert->get_ref(cert));
1021 }
1022 enumerator->destroy(enumerator);
1023 enumerator = pkcs12->create_key_enumerator(pkcs12);
1024 while (enumerator->enumerate(enumerator, &key))
1025 {
1026 DBG1(DBG_CFG, " loaded %N private key from '%s'",
1027 key_type_names, key->get_type(key), path);
1028 secrets->add_key(secrets, key->get_ref(key));
1029 }
1030 enumerator->destroy(enumerator);
1031 pkcs12->container.destroy(&pkcs12->container);
1032 return TRUE;
1033 }
1034
1035 /**
1036 * Load a shared key
1037 */
1038 static bool load_shared(mem_cred_t *secrets, chunk_t line, int line_nr,
1039 shared_key_type_t type, chunk_t ids)
1040 {
1041 shared_key_t *shared_key;
1042 linked_list_t *owners;
1043 chunk_t secret = chunk_empty;
1044 bool any = TRUE;
1045
1046 err_t ugh = extract_secret(&secret, &line);
1047 if (ugh != NULL)
1048 {
1049 DBG1(DBG_CFG, "line %d: malformed secret: %s", line_nr, ugh);
1050 return FALSE;
1051 }
1052 shared_key = shared_key_create(type, secret);
1053 DBG1(DBG_CFG, " loaded %N secret for %s", shared_key_type_names, type,
1054 ids.len > 0 ? (char*)ids.ptr : "%any");
1055 DBG4(DBG_CFG, " secret: %#B", &secret);
1056
1057 owners = linked_list_create();
1058 while (ids.len > 0)
1059 {
1060 chunk_t id;
1061 identification_t *peer_id;
1062
1063 ugh = extract_value(&id, &ids);
1064 if (ugh != NULL)
1065 {
1066 DBG1(DBG_CFG, "line %d: %s", line_nr, ugh);
1067 shared_key->destroy(shared_key);
1068 owners->destroy_offset(owners, offsetof(identification_t, destroy));
1069 return FALSE;
1070 }
1071 if (id.len == 0)
1072 {
1073 continue;
1074 }
1075
1076 /* NULL terminate the ID string */
1077 *(id.ptr + id.len) = '\0';
1078 peer_id = identification_create_from_string(id.ptr);
1079 if (peer_id->get_type(peer_id) == ID_ANY)
1080 {
1081 peer_id->destroy(peer_id);
1082 continue;
1083 }
1084
1085 owners->insert_last(owners, peer_id);
1086 any = FALSE;
1087 }
1088 if (any)
1089 {
1090 owners->insert_last(owners,
1091 identification_create_from_encoding(ID_ANY, chunk_empty));
1092 }
1093 secrets->add_shared_list(secrets, shared_key, owners);
1094 return TRUE;
1095 }
1096
1097 /**
1098 * reload ipsec.secrets
1099 */
1100 static void load_secrets(private_stroke_cred_t *this, mem_cred_t *secrets,
1101 char *file, int level, FILE *prompt)
1102 {
1103 int line_nr = 0;
1104 chunk_t *src, line;
1105
1106 DBG1(DBG_CFG, "loading secrets from '%s'", file);
1107 src = chunk_map(file, FALSE);
1108 if (!src)
1109 {
1110 DBG1(DBG_CFG, "opening secrets file '%s' failed: %s", file,
1111 strerror(errno));
1112 return;
1113 }
1114
1115 if (!secrets)
1116 {
1117 secrets = mem_cred_create();
1118 }
1119
1120 while (fetchline(src, &line))
1121 {
1122 chunk_t ids, token;
1123 shared_key_type_t type;
1124
1125 line_nr++;
1126
1127 if (!eat_whitespace(&line))
1128 {
1129 continue;
1130 }
1131 if (line.len > strlen("include ") && strpfx(line.ptr, "include "))
1132 {
1133 char **expanded, *dir, pattern[PATH_MAX];
1134 u_char *pos;
1135
1136 if (level > MAX_SECRETS_RECURSION)
1137 {
1138 DBG1(DBG_CFG, "maximum level of %d includes reached, ignored",
1139 MAX_SECRETS_RECURSION);
1140 continue;
1141 }
1142 /* terminate filename by space */
1143 line = chunk_skip(line, strlen("include "));
1144 pos = memchr(line.ptr, ' ', line.len);
1145 if (pos)
1146 {
1147 line.len = pos - line.ptr;
1148 }
1149 if (line.len && line.ptr[0] == '/')
1150 {
1151 if (line.len + 1 > sizeof(pattern))
1152 {
1153 DBG1(DBG_CFG, "include pattern too long, ignored");
1154 continue;
1155 }
1156 snprintf(pattern, sizeof(pattern), "%.*s",
1157 (int)line.len, line.ptr);
1158 }
1159 else
1160 { /* use directory of current file if relative */
1161 dir = strdup(file);
1162 dir = dirname(dir);
1163
1164 if (line.len + 1 + strlen(dir) + 1 > sizeof(pattern))
1165 {
1166 DBG1(DBG_CFG, "include pattern too long, ignored");
1167 free(dir);
1168 continue;
1169 }
1170 snprintf(pattern, sizeof(pattern), "%s/%.*s",
1171 dir, (int)line.len, line.ptr);
1172 free(dir);
1173 }
1174 #ifdef HAVE_GLOB_H
1175 {
1176 glob_t buf;
1177 if (glob(pattern, GLOB_ERR, NULL, &buf) != 0)
1178 {
1179 DBG1(DBG_CFG, "expanding file expression '%s' failed",
1180 pattern);
1181 }
1182 else
1183 {
1184 for (expanded = buf.gl_pathv; *expanded != NULL; expanded++)
1185 {
1186 load_secrets(this, secrets, *expanded, level + 1,
1187 prompt);
1188 }
1189 }
1190 globfree(&buf);
1191 }
1192 #else /* HAVE_GLOB_H */
1193 /* if glob(3) is not available, try to load pattern directly */
1194 load_secrets(this, secrets, pattern, level + 1, prompt);
1195 #endif /* HAVE_GLOB_H */
1196 continue;
1197 }
1198
1199 if (line.len > 2 && strpfx(line.ptr, ": "))
1200 {
1201 /* no ids, skip the ':' */
1202 ids = chunk_empty;
1203 line.ptr++;
1204 line.len--;
1205 }
1206 else if (extract_token_str(&ids, " : ", &line))
1207 {
1208 /* NULL terminate the extracted id string */
1209 *(ids.ptr + ids.len) = '\0';
1210 }
1211 else
1212 {
1213 DBG1(DBG_CFG, "line %d: missing ' : ' separator", line_nr);
1214 break;
1215 }
1216
1217 if (!eat_whitespace(&line) || !extract_token(&token, ' ', &line))
1218 {
1219 DBG1(DBG_CFG, "line %d: missing token", line_nr);
1220 break;
1221 }
1222 if (match("RSA", &token) || match("ECDSA", &token))
1223 {
1224 if (!load_private(secrets, line, line_nr, prompt,
1225 match("RSA", &token) ? KEY_RSA : KEY_ECDSA))
1226 {
1227 break;
1228 }
1229 }
1230 else if (match("P12", &token))
1231 {
1232 if (!load_pkcs12(this, secrets, line, line_nr, prompt))
1233 {
1234 break;
1235 }
1236 }
1237 else if (match("PIN", &token))
1238 {
1239 if (!load_pin(secrets, line, line_nr, prompt))
1240 {
1241 break;
1242 }
1243 }
1244 else if ((match("PSK", &token) && (type = SHARED_IKE)) ||
1245 (match("EAP", &token) && (type = SHARED_EAP)) ||
1246 (match("NTLM", &token) && (type = SHARED_NT_HASH)) ||
1247 (match("XAUTH", &token) && (type = SHARED_EAP)))
1248 {
1249 if (!load_shared(secrets, line, line_nr, type, ids))
1250 {
1251 break;
1252 }
1253 }
1254 else
1255 {
1256 DBG1(DBG_CFG, "line %d: token must be either "
1257 "RSA, ECDSA, P12, PIN, PSK, EAP, XAUTH or NTLM", line_nr);
1258 break;
1259 }
1260 }
1261 chunk_unmap(src);
1262
1263 if (level == 0)
1264 { /* replace secrets in active credential set */
1265 this->creds->replace_secrets(this->creds, secrets, FALSE);
1266 secrets->destroy(secrets);
1267 }
1268 }
1269
1270 /**
1271 * load all certificates from ipsec.d
1272 */
1273 static void load_certs(private_stroke_cred_t *this)
1274 {
1275 DBG1(DBG_CFG, "loading ca certificates from '%s'",
1276 CA_CERTIFICATE_DIR);
1277 load_certdir(this, CA_CERTIFICATE_DIR, CERT_X509, X509_CA);
1278
1279 DBG1(DBG_CFG, "loading aa certificates from '%s'",
1280 AA_CERTIFICATE_DIR);
1281 load_certdir(this, AA_CERTIFICATE_DIR, CERT_X509, X509_AA);
1282
1283 DBG1(DBG_CFG, "loading ocsp signer certificates from '%s'",
1284 OCSP_CERTIFICATE_DIR);
1285 load_certdir(this, OCSP_CERTIFICATE_DIR, CERT_X509, X509_OCSP_SIGNER);
1286
1287 DBG1(DBG_CFG, "loading attribute certificates from '%s'",
1288 ATTR_CERTIFICATE_DIR);
1289 load_certdir(this, ATTR_CERTIFICATE_DIR, CERT_X509_AC, 0);
1290
1291 DBG1(DBG_CFG, "loading crls from '%s'",
1292 CRL_DIR);
1293 load_certdir(this, CRL_DIR, CERT_X509_CRL, 0);
1294 }
1295
1296 METHOD(stroke_cred_t, reread, void,
1297 private_stroke_cred_t *this, stroke_msg_t *msg, FILE *prompt)
1298 {
1299 if (msg->reread.flags & REREAD_SECRETS)
1300 {
1301 DBG1(DBG_CFG, "rereading secrets");
1302 load_secrets(this, NULL, SECRETS_FILE, 0, prompt);
1303 }
1304 if (msg->reread.flags & REREAD_CACERTS)
1305 {
1306 DBG1(DBG_CFG, "rereading ca certificates from '%s'",
1307 CA_CERTIFICATE_DIR);
1308 load_certdir(this, CA_CERTIFICATE_DIR, CERT_X509, X509_CA);
1309 }
1310 if (msg->reread.flags & REREAD_OCSPCERTS)
1311 {
1312 DBG1(DBG_CFG, "rereading ocsp signer certificates from '%s'",
1313 OCSP_CERTIFICATE_DIR);
1314 load_certdir(this, OCSP_CERTIFICATE_DIR, CERT_X509,
1315 X509_OCSP_SIGNER);
1316 }
1317 if (msg->reread.flags & REREAD_AACERTS)
1318 {
1319 DBG1(DBG_CFG, "rereading aa certificates from '%s'",
1320 AA_CERTIFICATE_DIR);
1321 load_certdir(this, AA_CERTIFICATE_DIR, CERT_X509, X509_AA);
1322 }
1323 if (msg->reread.flags & REREAD_ACERTS)
1324 {
1325 DBG1(DBG_CFG, "rereading attribute certificates from '%s'",
1326 ATTR_CERTIFICATE_DIR);
1327 load_certdir(this, ATTR_CERTIFICATE_DIR, CERT_X509_AC, 0);
1328 }
1329 if (msg->reread.flags & REREAD_CRLS)
1330 {
1331 DBG1(DBG_CFG, "rereading crls from '%s'",
1332 CRL_DIR);
1333 load_certdir(this, CRL_DIR, CERT_X509_CRL, 0);
1334 }
1335 }
1336
1337 METHOD(stroke_cred_t, add_shared, void,
1338 private_stroke_cred_t *this, shared_key_t *shared, linked_list_t *owners)
1339 {
1340 this->creds->add_shared_list(this->creds, shared, owners);
1341 }
1342
1343 METHOD(stroke_cred_t, destroy, void,
1344 private_stroke_cred_t *this)
1345 {
1346 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
1347 this->creds->destroy(this->creds);
1348 free(this);
1349 }
1350
1351 /*
1352 * see header file
1353 */
1354 stroke_cred_t *stroke_cred_create()
1355 {
1356 private_stroke_cred_t *this;
1357
1358 INIT(this,
1359 .public = {
1360 .set = {
1361 .create_private_enumerator = (void*)return_null,
1362 .create_cert_enumerator = (void*)return_null,
1363 .create_shared_enumerator = (void*)return_null,
1364 .create_cdp_enumerator = (void*)return_null,
1365 .cache_cert = (void*)_cache_cert,
1366 },
1367 .reread = _reread,
1368 .load_ca = _load_ca,
1369 .load_peer = _load_peer,
1370 .load_pubkey = _load_pubkey,
1371 .add_shared = _add_shared,
1372 .cachecrl = _cachecrl,
1373 .destroy = _destroy,
1374 },
1375 .creds = mem_cred_create(),
1376 );
1377
1378 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
1379
1380 this->force_ca_cert = lib->settings->get_bool(lib->settings,
1381 "%s.plugins.stroke.ignore_missing_ca_basic_constraint",
1382 FALSE, charon->name);
1383
1384 load_certs(this);
1385 load_secrets(this, NULL, SECRETS_FILE, 0, NULL);
1386
1387 return &this->public;
1388 }