implemented xauth as a pluto plugin
[strongswan.git] / src / pluto / keys.c
1 /* mechanisms for preshared keys (public, private, and preshared secrets)
2 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
3 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <time.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <resolv.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29
30 #include <glob.h>
31 #ifndef GLOB_ABORTED
32 # define GLOB_ABORTED GLOB_ABEND /* fix for old versions */
33 #endif
34
35 #include <freeswan.h>
36
37 #include <library.h>
38 #include <asn1/asn1.h>
39 #include <credentials/certificates/pgp_certificate.h>
40
41 #include "constants.h"
42 #include "defs.h"
43 #include "x509.h"
44 #include "certs.h"
45 #include "smartcard.h"
46 #include "connections.h"
47 #include "state.h"
48 #include "lex.h"
49 #include "keys.h"
50 #include "adns.h" /* needs <resolv.h> */
51 #include "dnskey.h" /* needs keys.h and adns.h */
52 #include "log.h"
53 #include "whack.h" /* for RC_LOG_SERIOUS */
54 #include "timer.h"
55 #include "fetch.h"
56
57 const char *shared_secrets_file = SHARED_SECRETS_FILE;
58
59
60 typedef enum secret_kind_t secret_kind_t;
61
62 enum secret_kind_t {
63 SECRET_PSK,
64 SECRET_PUBKEY,
65 SECRET_XAUTH,
66 SECRET_PIN
67 };
68
69 typedef struct secret_t secret_t;
70
71 struct secret_t {
72 linked_list_t *ids;
73 secret_kind_t kind;
74 union {
75 chunk_t preshared_secret;
76 private_key_t *private_key;
77 smartcard_t *smartcard;
78 } u;
79 secret_t *next;
80 };
81
82 /*
83 * free a public key struct
84 */
85 static void free_public_key(pubkey_t *pk)
86 {
87 DESTROY_IF(pk->id);
88 DESTROY_IF(pk->public_key);
89 DESTROY_IF(pk->issuer);
90 free(pk->serial.ptr);
91 free(pk);
92 }
93
94 secret_t *secrets = NULL;
95
96 /**
97 * Find the secret associated with the combination of me and the peer.
98 */
99 const secret_t* match_secret(identification_t *my_id, identification_t *his_id,
100 secret_kind_t kind)
101 {
102 enum { /* bits */
103 match_default = 0x01,
104 match_him = 0x02,
105 match_me = 0x04
106 };
107
108 unsigned int best_match = 0;
109 secret_t *s, *best = NULL;
110
111 for (s = secrets; s != NULL; s = s->next)
112 {
113 unsigned int match = 0;
114
115 if (s->kind != kind)
116 {
117 continue;
118 }
119
120 if (s->ids->get_count(s->ids) == 0)
121 {
122 /* a default (signified by lack of ids):
123 * accept if no more specific match found
124 */
125 match = match_default;
126 }
127 else
128 {
129 /* check if both ends match ids */
130 enumerator_t *enumerator;
131 identification_t *id;
132
133 enumerator = s->ids->create_enumerator(s->ids);
134 while (enumerator->enumerate(enumerator, &id))
135 {
136 if (my_id->equals(my_id, id))
137 {
138 match |= match_me;
139 }
140 if (his_id->equals(his_id, id))
141 {
142 match |= match_him;
143 }
144 }
145 enumerator->destroy(enumerator);
146
147 /* If our end matched the only id in the list,
148 * default to matching any peer.
149 * A more specific match will trump this.
150 */
151 if (match == match_me && s->ids->get_count(s->ids) == 1)
152 {
153 match |= match_default;
154 }
155 }
156
157 switch (match)
158 {
159 case match_me:
160 /* if this is an asymmetric (eg. public key) system,
161 * allow this-side-only match to count, even if
162 * there are other ids in the list.
163 */
164 if (kind != SECRET_PUBKEY)
165 {
166 break;
167 }
168 /* FALLTHROUGH */
169 case match_default: /* default all */
170 case match_me | match_default: /* default peer */
171 case match_me | match_him: /* explicit */
172 if (match == best_match)
173 {
174 /* two good matches are equally good: do they agree? */
175 bool same = FALSE;
176
177 switch (kind)
178 {
179 case SECRET_PSK:
180 case SECRET_XAUTH:
181 same = chunk_equals(s->u.preshared_secret,
182 best->u.preshared_secret);
183 break;
184 case SECRET_PUBKEY:
185 same = s->u.private_key->equals(s->u.private_key,
186 best->u.private_key);
187 break;
188 default:
189 bad_case(kind);
190 }
191 if (!same)
192 {
193 loglog(RC_LOG_SERIOUS, "multiple ipsec.secrets entries with "
194 "distinct secrets match endpoints: first secret used");
195 best = s; /* list is backwards: take latest in list */
196 }
197 }
198 else if (match > best_match)
199 {
200 /* this is the best match so far */
201 best_match = match;
202 best = s;
203 }
204 }
205 }
206 return best;
207 }
208
209 /**
210 * Retrieves an XAUTH secret primarily based on the user ID and
211 * secondarily based on the server ID
212 */
213 bool get_xauth_secret(identification_t *user, identification_t *server,
214 chunk_t *secret)
215 {
216 const secret_t *s;
217
218 s = match_secret(user, server, SECRET_XAUTH);
219 if (s)
220 {
221 *secret = chunk_clone(s->u.preshared_secret);
222 return TRUE;
223 }
224 else
225 {
226 *secret = chunk_empty;
227 return FALSE;
228 }
229 }
230
231 /**
232 * We match the ID (if none, the IP address). Failure is indicated by a NULL.
233 */
234 static const secret_t* get_secret(const connection_t *c, secret_kind_t kind)
235 {
236 identification_t *my_id, *his_id;
237 const secret_t *best;
238
239 my_id = c->spd.this.id;
240
241 if (his_id_was_instantiated(c))
242 {
243 /* roadwarrior: replace him with 0.0.0.0 */
244 his_id = identification_create_from_string("%any");
245 }
246 else if (kind == SECRET_PSK && (c->policy & (POLICY_PSK | POLICY_XAUTH_PSK)) &&
247 ((c->kind == CK_TEMPLATE &&
248 c->spd.that.id->get_type(c->spd.that.id) == ID_ANY) ||
249 (c->kind == CK_INSTANCE && id_is_ipaddr(c->spd.that.id))))
250 {
251 /* roadwarrior: replace him with 0.0.0.0 */
252 his_id = identification_create_from_string("%any");
253 }
254 else
255 {
256 his_id = c->spd.that.id->clone(c->spd.that.id);
257 }
258
259 best = match_secret(my_id, his_id, kind);
260
261 his_id->destroy(his_id);
262 return best;
263 }
264
265 /* find the appropriate preshared key (see get_secret).
266 * Failure is indicated by a NULL pointer.
267 * Note: the result is not to be freed by the caller.
268 */
269 const chunk_t* get_preshared_secret(const connection_t *c)
270 {
271 const secret_t *s = get_secret(c, SECRET_PSK);
272
273 DBG(DBG_PRIVATE,
274 if (s == NULL)
275 DBG_log("no Preshared Key Found");
276 else
277 DBG_dump_chunk("Preshared Key", s->u.preshared_secret);
278 )
279 return s == NULL? NULL : &s->u.preshared_secret;
280 }
281
282 /* check the existence of a private key matching a public key contained
283 * in an X.509 or OpenPGP certificate
284 */
285 bool has_private_key(cert_t *cert)
286 {
287 secret_t *s;
288 bool has_key = FALSE;
289 public_key_t *pub_key = cert->cert->get_public_key(cert->cert);
290
291 for (s = secrets; s != NULL; s = s->next)
292 {
293 if (s->kind == SECRET_PUBKEY &&
294 s->u.private_key->belongs_to(s->u.private_key, pub_key))
295 {
296 has_key = TRUE;
297 break;
298 }
299 }
300 pub_key->destroy(pub_key);
301 return has_key;
302 }
303
304 /*
305 * get the matching private key belonging to a given X.509 certificate
306 */
307 private_key_t* get_x509_private_key(const cert_t *cert)
308 {
309 public_key_t *public_key = cert->cert->get_public_key(cert->cert);
310 private_key_t *private_key = NULL;
311 secret_t *s;
312
313 for (s = secrets; s != NULL; s = s->next)
314 {
315
316 if (s->kind == SECRET_PUBKEY &&
317 s->u.private_key->belongs_to(s->u.private_key, public_key))
318 {
319 private_key = s->u.private_key;
320 break;
321 }
322 }
323 public_key->destroy(public_key);
324 return private_key;
325 }
326
327 /* find the appropriate private key (see get_secret).
328 * Failure is indicated by a NULL pointer.
329 */
330 private_key_t* get_private_key(const connection_t *c)
331 {
332 const secret_t *s, *best = NULL;
333
334 /* is a certificate assigned to this connection? */
335 if (c->spd.this.cert)
336 {
337 certificate_t *certificate;
338 public_key_t *pub_key;
339
340 certificate = c->spd.this.cert->cert;
341 pub_key = certificate->get_public_key(certificate);
342
343 for (s = secrets; s != NULL; s = s->next)
344 {
345 if (s->kind == SECRET_PUBKEY &&
346 s->u.private_key->belongs_to(s->u.private_key, pub_key))
347 {
348 best = s;
349 break; /* found the private key - no sense in searching further */
350 }
351 }
352 pub_key->destroy(pub_key);
353 }
354 else
355 {
356 best = get_secret(c, SECRET_PUBKEY);
357 }
358 return best ? best->u.private_key : NULL;
359 }
360
361 /* digest a secrets file
362 *
363 * The file is a sequence of records. A record is a maximal sequence of
364 * tokens such that the first, and only the first, is in the first column
365 * of a line.
366 *
367 * Tokens are generally separated by whitespace and are key words, ids,
368 * strings, or data suitable for ttodata(3). As a nod to convention,
369 * a trailing ":" on what would otherwise be a token is taken as a
370 * separate token. If preceded by whitespace, a "#" is taken as starting
371 * a comment: it and the rest of the line are ignored.
372 *
373 * One kind of record is an include directive. It starts with "include".
374 * The filename is the only other token in the record.
375 * If the filename does not start with /, it is taken to
376 * be relative to the directory containing the current file.
377 *
378 * The other kind of record describes a key. It starts with a
379 * sequence of ids and ends with key information. Each id
380 * is an IP address, a Fully Qualified Domain Name (which will immediately
381 * be resolved), or @FQDN which will be left as a name.
382 *
383 * The key part can be in several forms.
384 *
385 * The old form of the key is still supported: a simple
386 * quoted strings (with no escapes) is taken as a preshred key.
387 *
388 * The new form starts the key part with a ":".
389 *
390 * For Preshared Key, use the "PSK" keyword, and follow it by a string
391 * or a data token suitable for ttodata(3).
392 *
393 * For RSA Private Key, use the "RSA" keyword, followed by a
394 * brace-enclosed list of key field keywords and data values.
395 * The data values are large integers to be decoded by ttodata(3).
396 * The fields are a subset of those used by BIND 8.2 and have the
397 * same names.
398 */
399
400 /* parse PSK from file */
401 static err_t process_psk_secret(chunk_t *psk)
402 {
403 err_t ugh = NULL;
404
405 if (*tok == '"' || *tok == '\'')
406 {
407 chunk_t secret = { tok + 1, flp->cur - tok -2 };
408
409 *psk = chunk_clone(secret);
410 (void) shift();
411 }
412 else
413 {
414 char buf[BUF_LEN]; /* limit on size of binary representation of key */
415 size_t sz;
416
417 ugh = ttodatav(tok, flp->cur - tok, 0, buf, sizeof(buf), &sz
418 , diag_space, sizeof(diag_space), TTODATAV_SPACECOUNTS);
419 if (ugh != NULL)
420 {
421 /* ttodata didn't like PSK data */
422 ugh = builddiag("PSK data malformed (%s): %s", ugh, tok);
423 }
424 else
425 {
426 chunk_t secret = { buf, sz };
427 *psk = chunk_clone(secret);
428 (void) shift();
429 }
430 }
431 return ugh;
432 }
433
434 typedef enum rsa_private_key_part_t rsa_private_key_part_t;
435
436 enum rsa_private_key_part_t {
437 RSA_PART_MODULUS = 0,
438 RSA_PART_PUBLIC_EXPONENT = 1,
439 RSA_PART_PRIVATE_EXPONENT = 2,
440 RSA_PART_PRIME1 = 3,
441 RSA_PART_PRIME2 = 4,
442 RSA_PART_EXPONENT1 = 5,
443 RSA_PART_EXPONENT2 = 6,
444 RSA_PART_COEFFICIENT = 7
445 };
446
447 const char *rsa_private_key_part_names[] = {
448 "Modulus",
449 "PublicExponent",
450 "PrivateExponent",
451 "Prime1",
452 "Prime2",
453 "Exponent1",
454 "Exponent2",
455 "Coefficient"
456 };
457
458 /**
459 * Parse fields of an RSA private key in BIND 8.2's representation
460 * consistiong of a braced list of keyword and value pairs in required order.
461 */
462 static err_t process_rsa_secret(private_key_t **key)
463 {
464 chunk_t rsa_chunk[countof(rsa_private_key_part_names)];
465 u_char buf[RSA_MAX_ENCODING_BYTES]; /* limit on size of binary representation of key */
466 rsa_private_key_part_t part, p;
467 size_t sz;
468 err_t ugh;
469
470 for (part = RSA_PART_MODULUS; part <= RSA_PART_COEFFICIENT; part++)
471 {
472 const char *keyword = rsa_private_key_part_names[part];
473
474 if (!shift())
475 {
476 ugh = "premature end of RSA key";
477 goto end;
478 }
479 if (!tokeqword(keyword))
480 {
481 ugh = builddiag("%s keyword not found where expected in RSA key"
482 , keyword);
483 goto end;
484 }
485 if (!(shift() && (!tokeq(":") || shift()))) /* ignore optional ":" */
486 {
487 ugh = "premature end of RSA key";
488 goto end;
489 }
490 ugh = ttodatav(tok, flp->cur - tok, 0, buf, sizeof(buf), &sz,
491 diag_space, sizeof(diag_space), TTODATAV_SPACECOUNTS);
492 if (ugh)
493 {
494 ugh = builddiag("RSA data malformed (%s): %s", ugh, tok);
495 part++;
496 goto end;
497 }
498 rsa_chunk[part] = chunk_create(buf, sz);
499 rsa_chunk[part] = chunk_clone(rsa_chunk[part]);
500 }
501
502 /* We require an (indented) '}' and the end of the record.
503 * We break down the test so that the diagnostic will be more helpful.
504 * Some people don't seem to wish to indent the brace!
505 */
506 if (!shift() || !tokeq("}"))
507 {
508 ugh = "malformed end of RSA private key -- indented '}' required";
509 goto end;
510 }
511 if (shift())
512 {
513 ugh = "malformed end of RSA private key -- unexpected token after '}'";
514 goto end;
515 }
516
517 *key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
518 BUILD_RSA_MODULUS, rsa_chunk[RSA_PART_MODULUS],
519 BUILD_RSA_PUB_EXP, rsa_chunk[RSA_PART_PUBLIC_EXPONENT],
520 BUILD_RSA_PRIV_EXP, rsa_chunk[RSA_PART_PRIVATE_EXPONENT],
521 BUILD_RSA_PRIME1, rsa_chunk[RSA_PART_PRIME1],
522 BUILD_RSA_PRIME2, rsa_chunk[RSA_PART_PRIME2],
523 BUILD_RSA_EXP1, rsa_chunk[RSA_PART_EXPONENT1],
524 BUILD_RSA_EXP2, rsa_chunk[RSA_PART_EXPONENT2],
525 BUILD_RSA_COEFF, rsa_chunk[RSA_PART_COEFFICIENT],
526 BUILD_END);
527
528 if (*key == NULL)
529 {
530 ugh = "parsing of RSA private key failed";
531 }
532
533 end:
534 /* clean up and return */
535 for (p = RSA_PART_MODULUS ; p < part; p++)
536 {
537 chunk_clear(&rsa_chunk[p]);
538 }
539 return ugh;
540 }
541
542 /**
543 * process a key file protected with optional passphrase which can either be
544 * read from ipsec.secrets or prompted for by using whack
545 */
546 static err_t process_keyfile(private_key_t **key, key_type_t type, int whackfd)
547 {
548 char filename[BUF_LEN];
549 prompt_pass_t pass;
550
551 memset(filename,'\0', BUF_LEN);
552 memset(pass.secret,'\0', sizeof(pass.secret));
553 pass.prompt = FALSE;
554 pass.fd = whackfd;
555
556 /* we expect the filename of a PKCS#1 private key file */
557
558 if (*tok == '"' || *tok == '\'') /* quoted filename */
559 memcpy(filename, tok+1, flp->cur - tok - 2);
560 else
561 memcpy(filename, tok, flp->cur - tok);
562
563 if (shift())
564 {
565 /* we expect an appended passphrase or passphrase prompt*/
566 if (tokeqword("%prompt"))
567 {
568 if (pass.fd == NULL_FD)
569 {
570 return "Private key file -- enter passphrase using 'ipsec secrets'";
571 }
572 pass.prompt = TRUE;
573 }
574 else
575 {
576 char *passphrase = tok;
577 size_t len = flp->cur - passphrase;
578
579 if (*tok == '"' || *tok == '\'') /* quoted passphrase */
580 {
581 passphrase++;
582 len -= 2;
583 }
584 if (len > PROMPT_PASS_LEN)
585 {
586 return "Private key file -- passphrase exceeds 64 characters";
587 }
588 memcpy(pass.secret, passphrase, len);
589 }
590 if (shift())
591 {
592 return "Private key file -- unexpected token after passphrase";
593 }
594 }
595 *key = load_private_key(filename, &pass, type);
596
597 return *key ? NULL : "Private key file -- could not be loaded";
598 }
599
600 /**
601 * Process pin read from ipsec.secrets or prompted for it using whack
602 */
603 static err_t process_pin(secret_t *s, int whackfd)
604 {
605 smartcard_t *sc;
606 const char *pin_status = "no pin";
607
608 s->kind = SECRET_PIN;
609
610 /* looking for the smartcard keyword */
611 if (!shift() || strncmp(tok, SCX_TOKEN, strlen(SCX_TOKEN)) != 0)
612 return "PIN keyword must be followed by %smartcard<reader>:<id>";
613
614 sc = scx_add(scx_parse_number_slot_id(tok + strlen(SCX_TOKEN)));
615 s->u.smartcard = sc;
616 scx_share(sc);
617 if (sc->pin.ptr != NULL)
618 {
619 scx_release_context(sc);
620 scx_free_pin(&sc->pin);
621 }
622 sc->valid = FALSE;
623
624 if (!shift())
625 return "PIN statement must be terminated either by <pin code>, %pinpad or %prompt";
626
627 if (tokeqword("%prompt"))
628 {
629 shift();
630 /* if whackfd exists, whack will be used to prompt for a pin */
631 if (whackfd != NULL_FD)
632 pin_status = scx_get_pin(sc, whackfd) ? "valid pin" : "invalid pin";
633 else
634 pin_status = "pin entry via prompt";
635 }
636 else if (tokeqword("%pinpad"))
637 {
638 chunk_t empty_pin = { "", 0 };
639
640 shift();
641
642 /* pin will be entered via pin pad during verification */
643 sc->pin = chunk_clone(empty_pin);
644 sc->pinpad = TRUE;
645 sc->valid = TRUE;
646 pin_status = "pin entry via pad";
647 if (pkcs11_keep_state)
648 {
649 scx_verify_pin(sc);
650 }
651 }
652 else
653 {
654 /* we read the pin directly from ipsec.secrets */
655 err_t ugh = process_psk_secret(&sc->pin);
656 if (ugh != NULL)
657 return ugh;
658 /* verify the pin */
659 pin_status = scx_verify_pin(sc) ? "valid PIN" : "invalid PIN";
660 }
661 #ifdef SMARTCARD
662 {
663 char buf[BUF_LEN];
664
665 if (sc->any_slot)
666 snprintf(buf, BUF_LEN, "any slot");
667 else
668 snprintf(buf, BUF_LEN, "slot: %lu", sc->slot);
669
670 plog(" %s for #%d (%s, id: %s)"
671 , pin_status, sc->number, scx_print_slot(sc, ""), sc->id);
672 }
673 #else
674 plog(" warning: SMARTCARD support is deactivated in pluto/Makefile!");
675 #endif
676 return NULL;
677 }
678
679 static void log_psk(char *label, secret_t *s)
680 {
681 int n = 0;
682 char buf[BUF_LEN];
683 enumerator_t *enumerator;
684 identification_t *id;
685
686 if (s->ids->get_count(s->ids) == 0)
687 {
688 n = snprintf(buf, BUF_LEN, "%%any");
689 }
690 else
691 {
692 enumerator = s->ids->create_enumerator(s->ids);
693 while(enumerator->enumerate(enumerator, &id))
694 {
695 n += snprintf(buf + n, BUF_LEN - n, "%Y ", id);
696 if (n >= BUF_LEN)
697 {
698 n = BUF_LEN - 1;
699 break;
700 }
701 }
702 enumerator->destroy(enumerator);
703 }
704 plog(" loaded %s for %.*s", label, n, buf);
705 }
706
707 static void process_secret(secret_t *s, int whackfd)
708 {
709 err_t ugh = NULL;
710
711 s->kind = SECRET_PSK; /* default */
712 if (*tok == '"' || *tok == '\'')
713 {
714 log_psk("PSK", s);
715
716 /* old PSK format: just a string */
717 ugh = process_psk_secret(&s->u.preshared_secret);
718 }
719 else if (tokeqword("psk"))
720 {
721 log_psk("PSK", s);
722
723 /* preshared key: quoted string or ttodata format */
724 ugh = !shift()? "unexpected end of record in PSK"
725 : process_psk_secret(&s->u.preshared_secret);
726 }
727 else if (tokeqword("xauth"))
728 {
729 s->kind = SECRET_XAUTH;
730 log_psk("XAUTH", s);
731
732 /* xauth secret: quoted string or ttodata format */
733 ugh = !shift()? "unexpected end of record in XAUTH"
734 : process_psk_secret(&s->u.preshared_secret);
735 }
736 else if (tokeqword("rsa"))
737 {
738 /* RSA key: the fun begins.
739 * A braced list of keyword and value pairs.
740 */
741 s->kind = SECRET_PUBKEY;
742 if (!shift())
743 {
744 ugh = "bad RSA key syntax";
745 }
746 else if (tokeq("{"))
747 {
748 ugh = process_rsa_secret(&s->u.private_key);
749 }
750 else
751 {
752 ugh = process_keyfile(&s->u.private_key, KEY_RSA, whackfd);
753 }
754 }
755 else if (tokeqword("ecdsa"))
756 {
757 s->kind = SECRET_PUBKEY;
758 if (!shift())
759 {
760 ugh = "bad ECDSA key syntax";
761 }
762 else
763 {
764 ugh = process_keyfile(&s->u.private_key, KEY_ECDSA, whackfd);
765 }
766 }
767 else if (tokeqword("pin"))
768 {
769 ugh = process_pin(s, whackfd);
770 }
771 else
772 {
773 ugh = builddiag("unrecognized key format: %s", tok);
774 }
775
776 if (ugh != NULL)
777 {
778 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
779 , flp->filename, flp->lino, ugh);
780 free(s);
781 }
782 else if (flushline("expected record boundary in key"))
783 {
784 /* gauntlet has been run: install new secret */
785 lock_certs_and_keys("process_secret");
786 s->next = secrets;
787 secrets = s;
788 unlock_certs_and_keys("process_secrets");
789 }
790 }
791
792 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
793
794 static void process_secret_records(int whackfd)
795 {
796 /* read records from ipsec.secrets and load them into our table */
797 for (;;)
798 {
799 (void)flushline(NULL); /* silently ditch leftovers, if any */
800 if (flp->bdry == B_file)
801 {
802 break;
803 }
804 flp->bdry = B_none; /* eat the Record Boundary */
805 (void)shift(); /* get real first token */
806
807 if (tokeqword("include"))
808 {
809 /* an include directive */
810 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
811 char *p = fn;
812 char *end_prefix = strrchr(flp->filename, '/');
813
814 if (!shift())
815 {
816 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
817 , flp->filename, flp->lino);
818 continue; /* abandon this record */
819 }
820
821 /* if path is relative and including file's pathname has
822 * a non-empty dirname, prefix this path with that dirname.
823 */
824 if (tok[0] != '/' && end_prefix != NULL)
825 {
826 size_t pl = end_prefix - flp->filename + 1;
827
828 /* "clamp" length to prevent problems now;
829 * will be rediscovered and reported later.
830 */
831 if (pl > sizeof(fn))
832 {
833 pl = sizeof(fn);
834 }
835 memcpy(fn, flp->filename, pl);
836 p += pl;
837 }
838 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
839 {
840 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
841 , flp->filename, flp->lino);
842 continue; /* abandon this record */
843 }
844 strcpy(p, tok);
845 (void) shift(); /* move to Record Boundary, we hope */
846 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
847 {
848 process_secrets_file(fn, whackfd);
849 tok = NULL; /* correct, but probably redundant */
850 }
851 }
852 else
853 {
854 /* expecting a list of indices and then the key info */
855 secret_t *s = malloc_thing(secret_t);
856
857 zero(s);
858 s->ids = linked_list_create();
859 s->kind = SECRET_PSK; /* default */
860 s->u.preshared_secret = chunk_empty;
861 s->next = NULL;
862
863 for (;;)
864 {
865 if (tok[0] == '"' || tok[0] == '\'')
866 {
867 /* found key part */
868 process_secret(s, whackfd);
869 break;
870 }
871 else if (tokeq(":"))
872 {
873 /* found key part */
874 shift(); /* discard explicit separator */
875 process_secret(s, whackfd);
876 break;
877 }
878 else
879 {
880 identification_t *id;
881
882 id = identification_create_from_string(tok);
883 s->ids->insert_last(s->ids, id);
884
885 if (!shift())
886 {
887 /* unexpected Record Boundary or EOF */
888 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of id list"
889 , flp->filename, flp->lino);
890 break;
891 }
892 }
893 }
894 }
895 }
896 }
897
898 static int globugh(const char *epath, int eerrno)
899 {
900 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
901 return 1; /* stop glob */
902 }
903
904 static void process_secrets_file(const char *file_pat, int whackfd)
905 {
906 struct file_lex_position pos;
907 char **fnp;
908 glob_t globbuf;
909
910 pos.depth = flp == NULL? 0 : flp->depth + 1;
911
912 if (pos.depth > 10)
913 {
914 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
915 return;
916 }
917
918 /* do globbing */
919 {
920 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
921
922 if (r != 0)
923 {
924 switch (r)
925 {
926 case GLOB_NOSPACE:
927 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
928 break;
929 case GLOB_ABORTED:
930 break; /* already logged */
931 case GLOB_NOMATCH:
932 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
933 break;
934 default:
935 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
936 break;
937 }
938 globfree(&globbuf);
939 return;
940 }
941 }
942
943 /* for each file... */
944 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
945 {
946 if (lexopen(&pos, *fnp, FALSE))
947 {
948 plog("loading secrets from \"%s\"", *fnp);
949 (void) flushline("file starts with indentation (continuation notation)");
950 process_secret_records(whackfd);
951 lexclose();
952 }
953 }
954
955 globfree(&globbuf);
956 }
957
958 void free_preshared_secrets(void)
959 {
960 lock_certs_and_keys("free_preshared_secrets");
961
962 if (secrets != NULL)
963 {
964 secret_t *s, *ns;
965
966 plog("forgetting secrets");
967
968 for (s = secrets; s != NULL; s = ns)
969 {
970 ns = s->next;
971 s->ids->destroy_offset(s->ids, offsetof(identification_t, destroy));
972
973 switch (s->kind)
974 {
975 case SECRET_PSK:
976 case SECRET_XAUTH:
977 free(s->u.preshared_secret.ptr);
978 break;
979 case SECRET_PUBKEY:
980 DESTROY_IF(s->u.private_key);
981 break;
982 case SECRET_PIN:
983 scx_release(s->u.smartcard);
984 break;
985 default:
986 bad_case(s->kind);
987 }
988 free(s);
989 }
990 secrets = NULL;
991 }
992
993 unlock_certs_and_keys("free_preshard_secrets");
994 }
995
996 void load_preshared_secrets(int whackfd)
997 {
998 free_preshared_secrets();
999 (void) process_secrets_file(shared_secrets_file, whackfd);
1000 }
1001
1002 /* public key machinery
1003 * Note: caller must set dns_auth_level.
1004 */
1005
1006 pubkey_t* public_key_from_rsa(public_key_t *key)
1007 {
1008 pubkey_t *p = malloc_thing(pubkey_t);
1009
1010 zero(p);
1011 p->id = identification_create_from_string("%any"); /* don't know, doesn't matter */
1012 p->issuer = NULL;
1013 p->serial = chunk_empty;
1014 p->public_key = key;
1015
1016 /* note that we return a 1 reference count upon creation:
1017 * invariant: recount > 0.
1018 */
1019 p->refcnt = 1;
1020 return p;
1021 }
1022
1023 /* Free a public key record.
1024 * As a convenience, this returns a pointer to next.
1025 */
1026 pubkey_list_t* free_public_keyentry(pubkey_list_t *p)
1027 {
1028 pubkey_list_t *nxt = p->next;
1029
1030 if (p->key != NULL)
1031 {
1032 unreference_key(&p->key);
1033 }
1034 free(p);
1035 return nxt;
1036 }
1037
1038 void free_public_keys(pubkey_list_t **keys)
1039 {
1040 while (*keys != NULL)
1041 {
1042 *keys = free_public_keyentry(*keys);
1043 }
1044 }
1045
1046 /* root of chained public key list */
1047
1048 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1049
1050 void free_remembered_public_keys(void)
1051 {
1052 free_public_keys(&pubkeys);
1053 }
1054
1055 /**
1056 * Transfer public keys from *keys list to front of pubkeys list
1057 */
1058 void transfer_to_public_keys(struct gw_info *gateways_from_dns
1059 #ifdef USE_KEYRR
1060 , pubkey_list_t **keys
1061 #endif /* USE_KEYRR */
1062 )
1063 {
1064 {
1065 struct gw_info *gwp;
1066
1067 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1068 {
1069 pubkey_list_t *pl = malloc_thing(pubkey_list_t);
1070
1071 pl->key = gwp->key; /* note: this is a transfer */
1072 gwp->key = NULL; /* really, it is! */
1073 pl->next = pubkeys;
1074 pubkeys = pl;
1075 }
1076 }
1077
1078 #ifdef USE_KEYRR
1079 {
1080 pubkey_list_t **pp = keys;
1081
1082 while (*pp != NULL)
1083 {
1084 pp = &(*pp)->next;
1085 }
1086 *pp = pubkeys;
1087 pubkeys = *keys;
1088 *keys = NULL;
1089 }
1090 #endif /* USE_KEYRR */
1091 }
1092
1093
1094 static void install_public_key(pubkey_t *pk, pubkey_list_t **head)
1095 {
1096 pubkey_list_t *p = malloc_thing(pubkey_list_t);
1097
1098 /* install new key at front */
1099 p->key = reference_key(pk);
1100 p->next = *head;
1101 *head = p;
1102 }
1103
1104 void delete_public_keys(identification_t *id, key_type_t type,
1105 identification_t *issuer, chunk_t serial)
1106 {
1107 pubkey_list_t **pp, *p;
1108 pubkey_t *pk;
1109 key_type_t pk_type;
1110
1111 for (pp = &pubkeys; (p = *pp) != NULL; )
1112 {
1113 pk = p->key;
1114 pk_type = pk->public_key->get_type(pk->public_key);
1115
1116 if (id->equals(id, pk->id) && pk_type == type
1117 && (issuer == NULL || pk->issuer == NULL
1118 || issuer->equals(issuer, pk->issuer))
1119 && (serial.ptr == NULL || chunk_equals(serial, pk->serial)))
1120 {
1121 *pp = free_public_keyentry(p);
1122 }
1123 else
1124 {
1125 pp = &p->next;
1126 }
1127 }
1128 }
1129
1130 pubkey_t* reference_key(pubkey_t *pk)
1131 {
1132 DBG(DBG_CONTROLMORE,
1133 DBG_log(" ref key: %p %p cnt %d '%Y'",
1134 pk, pk->public_key, pk->refcnt, pk->id)
1135 )
1136 pk->refcnt++;
1137 return pk;
1138 }
1139
1140 void unreference_key(pubkey_t **pkp)
1141 {
1142 pubkey_t *pk = *pkp;
1143
1144 if (pk == NULL)
1145 {
1146 return;
1147 }
1148
1149 DBG(DBG_CONTROLMORE,
1150 DBG_log("unref key: %p %p cnt %d '%Y'",
1151 pk, pk->public_key, pk->refcnt, pk->id)
1152 )
1153
1154 /* cancel out the pointer */
1155 *pkp = NULL;
1156
1157 passert(pk->refcnt != 0);
1158 pk->refcnt--;
1159 if (pk->refcnt == 0)
1160 {
1161 free_public_key(pk);
1162 }
1163 }
1164
1165 bool add_public_key(identification_t *id, enum dns_auth_level dns_auth_level,
1166 enum pubkey_alg alg, chunk_t rfc3110_key,
1167 pubkey_list_t **head)
1168 {
1169 public_key_t *key = NULL;
1170 pubkey_t *pk;
1171
1172 /* first: algorithm-specific decoding of key chunk */
1173 switch (alg)
1174 {
1175 case PUBKEY_ALG_RSA:
1176 key = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
1177 BUILD_BLOB_DNSKEY, rfc3110_key,
1178 BUILD_END);
1179 if (key == NULL)
1180 {
1181 return FALSE;
1182 }
1183 break;
1184 default:
1185 bad_case(alg);
1186 }
1187
1188 pk = malloc_thing(pubkey_t);
1189 zero(pk);
1190 pk->public_key = key;
1191 pk->id = id->clone(id);
1192 pk->dns_auth_level = dns_auth_level;
1193 pk->until_time = UNDEFINED_TIME;
1194 pk->issuer = NULL;
1195 pk->serial = chunk_empty;
1196 install_public_key(pk, head);
1197 return TRUE;
1198 }
1199
1200 /**
1201 * Extract id and public key a certificate and insert it into a pubkeyrec
1202 */
1203 void add_public_key_from_cert(cert_t *cert , time_t until,
1204 enum dns_auth_level dns_auth_level)
1205 {
1206 certificate_t *certificate = cert->cert;
1207 identification_t *subject = certificate->get_subject(certificate);
1208 identification_t *issuer = NULL;
1209 identification_t *id;
1210 chunk_t serialNumber = chunk_empty;
1211 pubkey_t *pk;
1212 key_type_t pk_type;
1213
1214 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1215 pk = malloc_thing(pubkey_t);
1216 zero(pk);
1217 pk->public_key = certificate->get_public_key(certificate);
1218 pk_type = pk->public_key->get_type(pk->public_key);
1219 pk->id = subject->clone(subject);
1220 pk->dns_auth_level = dns_auth_level;
1221 pk->until_time = until;
1222 if (certificate->get_type(certificate) == CERT_X509)
1223 {
1224 x509_t *x509 = (x509_t*)certificate;
1225
1226 issuer = certificate->get_issuer(certificate);
1227 serialNumber = x509->get_serial(x509);
1228 pk->issuer = issuer->clone(issuer);
1229 pk->serial = chunk_clone(serialNumber);
1230 }
1231 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1232 install_public_key(pk, &pubkeys);
1233
1234 if (certificate->get_type(certificate) == CERT_X509)
1235 {
1236 x509_t *x509 = (x509_t*)certificate;
1237 enumerator_t *enumerator;
1238
1239 /* insert all subjectAltNames from X.509 certificates */
1240 enumerator = x509->create_subjectAltName_enumerator(x509);
1241 while (enumerator->enumerate(enumerator, &id))
1242 {
1243 if (id->get_type(id) != ID_ANY)
1244 {
1245 pk = malloc_thing(pubkey_t);
1246 zero(pk);
1247 pk->id = id->clone(id);
1248 pk->public_key = certificate->get_public_key(certificate);
1249 pk->dns_auth_level = dns_auth_level;
1250 pk->until_time = until;
1251 pk->issuer = issuer->clone(issuer);
1252 pk->serial = chunk_clone(serialNumber);
1253 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1254 install_public_key(pk, &pubkeys);
1255 }
1256 }
1257 enumerator->destroy(enumerator);
1258 }
1259 else
1260 {
1261 pgp_certificate_t *pgp_cert = (pgp_certificate_t*)certificate;
1262 chunk_t fingerprint = pgp_cert->get_fingerprint(pgp_cert);
1263
1264 /* add v3 or v4 PGP fingerprint */
1265 pk = malloc_thing(pubkey_t);
1266 zero(pk);
1267 pk->id = identification_create_from_encoding(ID_KEY_ID, fingerprint);
1268 pk->public_key = certificate->get_public_key(certificate);
1269 pk->dns_auth_level = dns_auth_level;
1270 pk->until_time = until;
1271 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1272 install_public_key(pk, &pubkeys);
1273 }
1274 }
1275
1276 /* when a X.509 certificate gets revoked, all instances of
1277 * the corresponding public key must be removed
1278 */
1279 void remove_x509_public_key(const cert_t *cert)
1280 {
1281 public_key_t *revoked_key = cert->cert->get_public_key(cert->cert);
1282 pubkey_list_t *p, **pp;
1283
1284 p = pubkeys;
1285 pp = &pubkeys;
1286
1287 while(p != NULL)
1288 {
1289 if (revoked_key->equals(revoked_key, p->key->public_key))
1290 {
1291 /* remove p from list and free memory */
1292 *pp = free_public_keyentry(p);
1293 loglog(RC_LOG_SERIOUS, "invalid public key deleted");
1294 }
1295 else
1296 {
1297 pp = &p->next;
1298 }
1299 p =*pp;
1300 }
1301 revoked_key->destroy(revoked_key);
1302 }
1303
1304 /*
1305 * list all public keys in the chained list
1306 */
1307 void list_public_keys(bool utc)
1308 {
1309 pubkey_list_t *p = pubkeys;
1310
1311 if (p != NULL)
1312 {
1313 whack_log(RC_COMMENT, " ");
1314 whack_log(RC_COMMENT, "List of Public Keys:");
1315 }
1316
1317 while (p != NULL)
1318 {
1319 pubkey_t *key = p->key;
1320 public_key_t *public = key->public_key;
1321 chunk_t keyid;
1322
1323 whack_log(RC_COMMENT, " ");
1324 whack_log(RC_COMMENT, " identity: '%Y'", key->id);
1325 whack_log(RC_COMMENT, " pubkey: %N %4d bits, until %T %s",
1326 key_type_names, public->get_type(public),
1327 public->get_keysize(public) * BITS_PER_BYTE,
1328 &key->until_time, utc,
1329 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1330 if (public->get_fingerprint(public, KEY_ID_PUBKEY_INFO_SHA1, &keyid))
1331 {
1332 whack_log(RC_COMMENT," keyid: %#B", &keyid);
1333 }
1334 if (key->issuer)
1335 {
1336 whack_log(RC_COMMENT," issuer: \"%Y\"", key->issuer);
1337 }
1338 if (key->serial.len)
1339 {
1340 whack_log(RC_COMMENT," serial: %#B", &key->serial);
1341 }
1342 p = p->next;
1343 }
1344 }