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