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