ASN.1 DER encoding of private key is not needed anymore
[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 */
412 static err_t process_rsa_secret(private_key_t **key)
413 {
414 chunk_t rsa_chunk[countof(rsa_private_key_part_names)];
415 u_char buf[RSA_MAX_ENCODING_BYTES]; /* limit on size of binary representation of key */
416 rsa_private_key_part_t part, p;
417 size_t sz;
418 err_t ugh;
419
420 for (part = RSA_PART_MODULUS; part <= RSA_PART_COEFFICIENT; part++)
421 {
422 const char *keyword = rsa_private_key_part_names[part];
423
424 if (!shift())
425 {
426 ugh = "premature end of RSA key";
427 goto end;
428 }
429 if (!tokeqword(keyword))
430 {
431 ugh = builddiag("%s keyword not found where expected in RSA key"
432 , keyword);
433 goto end;
434 }
435 if (!(shift() && (!tokeq(":") || shift()))) /* ignore optional ":" */
436 {
437 ugh = "premature end of RSA key";
438 goto end;
439 }
440 ugh = ttodatav(tok, flp->cur - tok, 0, buf, sizeof(buf), &sz,
441 diag_space, sizeof(diag_space), TTODATAV_SPACECOUNTS);
442 if (ugh)
443 {
444 ugh = builddiag("RSA data malformed (%s): %s", ugh, tok);
445 part++;
446 goto end;
447 }
448 rsa_chunk[part] = chunk_create(buf, sz);
449 rsa_chunk[part] = chunk_clone(rsa_chunk[part]);
450 }
451
452 /* We require an (indented) '}' and the end of the record.
453 * We break down the test so that the diagnostic will be more helpful.
454 * Some people don't seem to wish to indent the brace!
455 */
456 if (!shift() || !tokeq("}"))
457 {
458 ugh = "malformed end of RSA private key -- indented '}' required";
459 goto end;
460 }
461 if (shift())
462 {
463 ugh = "malformed end of RSA private key -- unexpected token after '}'";
464 goto end;
465 }
466
467 *key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
468 BUILD_RSA_MODULUS, rsa_chunk[RSA_PART_MODULUS],
469 BUILD_RSA_PUB_EXP, rsa_chunk[RSA_PART_PUBLIC_EXPONENT],
470 BUILD_RSA_PRIV_EXP, rsa_chunk[RSA_PART_PRIVATE_EXPONENT],
471 BUILD_RSA_PRIME1, rsa_chunk[RSA_PART_PRIME1],
472 BUILD_RSA_PRIME2, rsa_chunk[RSA_PART_PRIME2],
473 BUILD_RSA_EXP1, rsa_chunk[RSA_PART_EXPONENT1],
474 BUILD_RSA_EXP2, rsa_chunk[RSA_PART_EXPONENT2],
475 BUILD_RSA_COEFF, rsa_chunk[RSA_PART_COEFFICIENT],
476 BUILD_END);
477
478 if (*key == NULL)
479 {
480 ugh = "parsing of RSA private key failed";
481 }
482
483 end:
484 /* clean up and return */
485 for (p = RSA_PART_MODULUS ; p < part; p++)
486 {
487 free(rsa_chunk[p].ptr);
488 }
489 return ugh;
490 }
491
492 /**
493 * process a key file protected with optional passphrase which can either be
494 * read from ipsec.secrets or prompted for by using whack
495 */
496 static err_t process_keyfile(private_key_t **key, key_type_t type, int whackfd)
497 {
498 char filename[BUF_LEN];
499 prompt_pass_t pass;
500
501 memset(filename,'\0', BUF_LEN);
502 memset(pass.secret,'\0', sizeof(pass.secret));
503 pass.prompt = FALSE;
504 pass.fd = whackfd;
505
506 /* we expect the filename of a PKCS#1 private key file */
507
508 if (*tok == '"' || *tok == '\'') /* quoted filename */
509 memcpy(filename, tok+1, flp->cur - tok - 2);
510 else
511 memcpy(filename, tok, flp->cur - tok);
512
513 if (shift())
514 {
515 /* we expect an appended passphrase or passphrase prompt*/
516 if (tokeqword("%prompt"))
517 {
518 if (pass.fd == NULL_FD)
519 {
520 return "Private key file -- enter passphrase using 'ipsec secrets'";
521 }
522 pass.prompt = TRUE;
523 }
524 else
525 {
526 char *passphrase = tok;
527 size_t len = flp->cur - passphrase;
528
529 if (*tok == '"' || *tok == '\'') /* quoted passphrase */
530 {
531 passphrase++;
532 len -= 2;
533 }
534 if (len > PROMPT_PASS_LEN)
535 {
536 return "Private key file -- passphrase exceeds 64 characters";
537 }
538 memcpy(pass.secret, passphrase, len);
539 }
540 if (shift())
541 {
542 return "Private key file -- unexpected token after passphrase";
543 }
544 }
545 *key = load_private_key(filename, &pass, type);
546
547 return *key ? NULL : "Private key file -- could not be loaded";
548 }
549
550 /**
551 * Process xauth secret read from ipsec.secrets
552 */
553 static err_t process_xauth(secret_t *s)
554 {
555 chunk_t user_name;
556
557 s->kind = PPK_XAUTH;
558
559 if (!shift())
560 return "missing xauth user name";
561 if (*tok == '"' || *tok == '\'') /* quoted user name */
562 {
563 user_name.ptr = tok + 1;
564 user_name.len = flp->cur - tok - 2;
565 }
566 else
567 {
568 user_name.ptr = tok;
569 user_name.len = flp->cur - tok;
570 }
571 plog(" loaded xauth credentials of user '%.*s'"
572 , user_name.len
573 , user_name.ptr);
574 s->u.xauth_secret.user_name = chunk_clone(user_name);
575
576 if (!shift())
577 return "missing xauth user password";
578 return process_psk_secret(&s->u.xauth_secret.user_password);
579 }
580
581 /**
582 * Get XAUTH secret from chained secrets lists
583 * only one entry is currently supported
584 */
585 static bool xauth_get_secret(xauth_t *xauth_secret)
586 {
587 secret_t *s;
588 bool found = FALSE;
589
590 for (s = secrets; s != NULL; s = s->next)
591 {
592 if (s->kind == PPK_XAUTH)
593 {
594 if (found)
595 {
596 plog("found multiple xauth secrets - first selected");
597 }
598 else
599 {
600 found = TRUE;
601 *xauth_secret = s->u.xauth_secret;
602 }
603 }
604 }
605 return found;
606 }
607
608 /**
609 * find a matching secret
610 */
611 static bool xauth_verify_secret(const xauth_peer_t *peer,
612 const xauth_t *xauth_secret)
613 {
614 bool found = FALSE;
615 secret_t *s;
616
617 for (s = secrets; s != NULL; s = s->next)
618 {
619 if (s->kind == PPK_XAUTH)
620 {
621 if (!chunk_equals(xauth_secret->user_name, s->u.xauth_secret.user_name))
622 {
623 continue;
624 }
625 found = TRUE;
626 if (chunk_equals(xauth_secret->user_password, s->u.xauth_secret.user_password))
627 {
628 return TRUE;
629 }
630 }
631 }
632 plog("xauth user '%.*s' %s"
633 , xauth_secret->user_name.len, xauth_secret->user_name.ptr
634 , found? "sent wrong password":"not found");
635 return FALSE;
636 }
637
638 /**
639 * the global xauth_module struct is defined here
640 */
641 xauth_module_t xauth_module;
642
643 /**
644 * Assign the default xauth functions to any null function pointers
645 */
646 void xauth_defaults(void)
647 {
648 if (xauth_module.get_secret == NULL)
649 {
650 DBG(DBG_CONTROL,
651 DBG_log("xauth module: using default get_secret() function")
652 )
653 xauth_module.get_secret = xauth_get_secret;
654 }
655 if (xauth_module.verify_secret == NULL)
656 {
657 DBG(DBG_CONTROL,
658 DBG_log("xauth module: using default verify_secret() function")
659 )
660 xauth_module.verify_secret = xauth_verify_secret;
661 }
662 };
663
664 /**
665 * Process pin read from ipsec.secrets or prompted for it using whack
666 */
667 static err_t process_pin(secret_t *s, int whackfd)
668 {
669 smartcard_t *sc;
670 const char *pin_status = "no pin";
671
672 s->kind = PPK_PIN;
673
674 /* looking for the smartcard keyword */
675 if (!shift() || strncmp(tok, SCX_TOKEN, strlen(SCX_TOKEN)) != 0)
676 return "PIN keyword must be followed by %smartcard<reader>:<id>";
677
678 sc = scx_add(scx_parse_number_slot_id(tok + strlen(SCX_TOKEN)));
679 s->u.smartcard = sc;
680 scx_share(sc);
681 if (sc->pin.ptr != NULL)
682 {
683 scx_release_context(sc);
684 scx_free_pin(&sc->pin);
685 }
686 sc->valid = FALSE;
687
688 if (!shift())
689 return "PIN statement must be terminated either by <pin code>, %pinpad or %prompt";
690
691 if (tokeqword("%prompt"))
692 {
693 shift();
694 /* if whackfd exists, whack will be used to prompt for a pin */
695 if (whackfd != NULL_FD)
696 pin_status = scx_get_pin(sc, whackfd) ? "valid pin" : "invalid pin";
697 else
698 pin_status = "pin entry via prompt";
699 }
700 else if (tokeqword("%pinpad"))
701 {
702 chunk_t empty_pin = { "", 0 };
703
704 shift();
705
706 /* pin will be entered via pin pad during verification */
707 sc->pin = chunk_clone(empty_pin);
708 sc->pinpad = TRUE;
709 sc->valid = TRUE;
710 pin_status = "pin entry via pad";
711 if (pkcs11_keep_state)
712 {
713 scx_verify_pin(sc);
714 }
715 }
716 else
717 {
718 /* we read the pin directly from ipsec.secrets */
719 err_t ugh = process_psk_secret(&sc->pin);
720 if (ugh != NULL)
721 return ugh;
722 /* verify the pin */
723 pin_status = scx_verify_pin(sc) ? "valid PIN" : "invalid PIN";
724 }
725 #ifdef SMARTCARD
726 {
727 char buf[BUF_LEN];
728
729 if (sc->any_slot)
730 snprintf(buf, BUF_LEN, "any slot");
731 else
732 snprintf(buf, BUF_LEN, "slot: %lu", sc->slot);
733
734 plog(" %s for #%d (%s, id: %s)"
735 , pin_status, sc->number, scx_print_slot(sc, ""), sc->id);
736 }
737 #else
738 plog(" warning: SMARTCARD support is deactivated in pluto/Makefile!");
739 #endif
740 return NULL;
741 }
742
743 static void log_psk(secret_t *s)
744 {
745 int n = 0;
746 char buf[BUF_LEN];
747 id_list_t *id_list = s->ids;
748
749 if (id_list == NULL)
750 {
751 n = snprintf(buf, BUF_LEN, "%%any");
752 }
753 else
754 {
755 do
756 {
757 n += idtoa(&id_list->id, buf + n, BUF_LEN - n);
758 if (n >= BUF_LEN)
759 {
760 n = BUF_LEN - 1;
761 break;
762 }
763 else if (n < BUF_LEN - 1)
764 {
765 n += snprintf(buf + n, BUF_LEN - n, " ");
766 }
767 id_list = id_list->next;
768 }
769 while (id_list);
770 }
771 plog(" loaded shared key for %.*s", n, buf);
772 }
773
774 static void process_secret(secret_t *s, int whackfd)
775 {
776 err_t ugh = NULL;
777
778 s->kind = PPK_PSK; /* default */
779 if (*tok == '"' || *tok == '\'')
780 {
781 /* old PSK format: just a string */
782 log_psk(s);
783 ugh = process_psk_secret(&s->u.preshared_secret);
784 }
785 else if (tokeqword("psk"))
786 {
787 /* preshared key: quoted string or ttodata format */
788 log_psk(s);
789 ugh = !shift()? "unexpected end of record in PSK"
790 : process_psk_secret(&s->u.preshared_secret);
791 }
792 else if (tokeqword("rsa"))
793 {
794 /* RSA key: the fun begins.
795 * A braced list of keyword and value pairs.
796 */
797 s->kind = PPK_PUBKEY;
798 if (!shift())
799 {
800 ugh = "bad RSA key syntax";
801 }
802 else if (tokeq("{"))
803 {
804 ugh = process_rsa_secret(&s->u.private_key);
805 }
806 else
807 {
808 ugh = process_keyfile(&s->u.private_key, KEY_RSA, whackfd);
809 }
810 }
811 else if (tokeqword("ecdsa"))
812 {
813 s->kind = PPK_PUBKEY;
814 if (!shift())
815 {
816 ugh = "bad ECDSA key syntax";
817 }
818 else
819 {
820 ugh = process_keyfile(&s->u.private_key, KEY_ECDSA, whackfd);
821 }
822 }
823 else if (tokeqword("xauth"))
824 {
825 ugh = process_xauth(s);
826 }
827 else if (tokeqword("pin"))
828 {
829 ugh = process_pin(s, whackfd);
830 }
831 else
832 {
833 ugh = builddiag("unrecognized key format: %s", tok);
834 }
835
836 if (ugh != NULL)
837 {
838 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
839 , flp->filename, flp->lino, ugh);
840 free(s);
841 }
842 else if (flushline("expected record boundary in key"))
843 {
844 /* gauntlet has been run: install new secret */
845 lock_certs_and_keys("process_secret");
846 s->next = secrets;
847 secrets = s;
848 unlock_certs_and_keys("process_secrets");
849 }
850 }
851
852 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
853
854 static void process_secret_records(int whackfd)
855 {
856 /* read records from ipsec.secrets and load them into our table */
857 for (;;)
858 {
859 (void)flushline(NULL); /* silently ditch leftovers, if any */
860 if (flp->bdry == B_file)
861 {
862 break;
863 }
864 flp->bdry = B_none; /* eat the Record Boundary */
865 (void)shift(); /* get real first token */
866
867 if (tokeqword("include"))
868 {
869 /* an include directive */
870 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
871 char *p = fn;
872 char *end_prefix = strrchr(flp->filename, '/');
873
874 if (!shift())
875 {
876 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
877 , flp->filename, flp->lino);
878 continue; /* abandon this record */
879 }
880
881 /* if path is relative and including file's pathname has
882 * a non-empty dirname, prefix this path with that dirname.
883 */
884 if (tok[0] != '/' && end_prefix != NULL)
885 {
886 size_t pl = end_prefix - flp->filename + 1;
887
888 /* "clamp" length to prevent problems now;
889 * will be rediscovered and reported later.
890 */
891 if (pl > sizeof(fn))
892 {
893 pl = sizeof(fn);
894 }
895 memcpy(fn, flp->filename, pl);
896 p += pl;
897 }
898 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
899 {
900 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
901 , flp->filename, flp->lino);
902 continue; /* abandon this record */
903 }
904 strcpy(p, tok);
905 (void) shift(); /* move to Record Boundary, we hope */
906 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
907 {
908 process_secrets_file(fn, whackfd);
909 tok = NULL; /* correct, but probably redundant */
910 }
911 }
912 else
913 {
914 /* expecting a list of indices and then the key info */
915 secret_t *s = malloc_thing(secret_t);
916
917 zero(s);
918 s->ids = NULL;
919 s->kind = PPK_PSK; /* default */
920 s->u.preshared_secret = chunk_empty;
921 s->next = NULL;
922
923 for (;;)
924 {
925 if (tok[0] == '"' || tok[0] == '\'')
926 {
927 /* found key part */
928 process_secret(s, whackfd);
929 break;
930 }
931 else if (tokeq(":"))
932 {
933 /* found key part */
934 shift(); /* discard explicit separator */
935 process_secret(s, whackfd);
936 break;
937 }
938 else
939 {
940 /* an id
941 * See RFC2407 IPsec Domain of Interpretation 4.6.2
942 */
943 struct id id;
944 err_t ugh;
945
946 if (tokeq("%any"))
947 {
948 id = empty_id;
949 id.kind = ID_IPV4_ADDR;
950 ugh = anyaddr(AF_INET, &id.ip_addr);
951 }
952 else if (tokeq("%any6"))
953 {
954 id = empty_id;
955 id.kind = ID_IPV6_ADDR;
956 ugh = anyaddr(AF_INET6, &id.ip_addr);
957 }
958 else
959 {
960 ugh = atoid(tok, &id, FALSE);
961 }
962
963 if (ugh != NULL)
964 {
965 loglog(RC_LOG_SERIOUS
966 , "ERROR \"%s\" line %d: index \"%s\" %s"
967 , flp->filename, flp->lino, tok, ugh);
968 }
969 else
970 {
971 id_list_t *i = malloc_thing(id_list_t);
972
973 i->id = id;
974 unshare_id_content(&i->id);
975 i->next = s->ids;
976 s->ids = i;
977 /* DBG_log("id type %d: %s %.*s", i->kind, ip_str(&i->ip_addr), (int)i->name.len, i->name.ptr); */
978 }
979 if (!shift())
980 {
981 /* unexpected Record Boundary or EOF */
982 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of id list"
983 , flp->filename, flp->lino);
984 break;
985 }
986 }
987 }
988 }
989 }
990 }
991
992 static int globugh(const char *epath, int eerrno)
993 {
994 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
995 return 1; /* stop glob */
996 }
997
998 static void process_secrets_file(const char *file_pat, int whackfd)
999 {
1000 struct file_lex_position pos;
1001 char **fnp;
1002 glob_t globbuf;
1003
1004 pos.depth = flp == NULL? 0 : flp->depth + 1;
1005
1006 if (pos.depth > 10)
1007 {
1008 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
1009 return;
1010 }
1011
1012 /* do globbing */
1013 {
1014 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1015
1016 if (r != 0)
1017 {
1018 switch (r)
1019 {
1020 case GLOB_NOSPACE:
1021 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1022 break;
1023 case GLOB_ABORTED:
1024 break; /* already logged */
1025 case GLOB_NOMATCH:
1026 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1027 break;
1028 default:
1029 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1030 break;
1031 }
1032 globfree(&globbuf);
1033 return;
1034 }
1035 }
1036
1037 /* for each file... */
1038 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1039 {
1040 if (lexopen(&pos, *fnp, FALSE))
1041 {
1042 plog("loading secrets from \"%s\"", *fnp);
1043 (void) flushline("file starts with indentation (continuation notation)");
1044 process_secret_records(whackfd);
1045 lexclose();
1046 }
1047 }
1048
1049 globfree(&globbuf);
1050 }
1051
1052 void free_preshared_secrets(void)
1053 {
1054 lock_certs_and_keys("free_preshared_secrets");
1055
1056 if (secrets != NULL)
1057 {
1058 secret_t *s, *ns;
1059
1060 plog("forgetting secrets");
1061
1062 for (s = secrets; s != NULL; s = ns)
1063 {
1064 id_list_t *i, *ni;
1065
1066 ns = s->next; /* grab before freeing s */
1067 for (i = s->ids; i != NULL; i = ni)
1068 {
1069 ni = i->next; /* grab before freeing i */
1070 free_id_content(&i->id);
1071 free(i);
1072 }
1073 switch (s->kind)
1074 {
1075 case PPK_PSK:
1076 free(s->u.preshared_secret.ptr);
1077 break;
1078 case PPK_PUBKEY:
1079 DESTROY_IF(s->u.private_key);
1080 break;
1081 case PPK_XAUTH:
1082 free(s->u.xauth_secret.user_name.ptr);
1083 free(s->u.xauth_secret.user_password.ptr);
1084 break;
1085 case PPK_PIN:
1086 scx_release(s->u.smartcard);
1087 break;
1088 default:
1089 bad_case(s->kind);
1090 }
1091 free(s);
1092 }
1093 secrets = NULL;
1094 }
1095
1096 unlock_certs_and_keys("free_preshard_secrets");
1097 }
1098
1099 void load_preshared_secrets(int whackfd)
1100 {
1101 free_preshared_secrets();
1102 (void) process_secrets_file(shared_secrets_file, whackfd);
1103 }
1104
1105 /* public key machinery
1106 * Note: caller must set dns_auth_level.
1107 */
1108
1109 pubkey_t* public_key_from_rsa(public_key_t *key)
1110 {
1111 pubkey_t *p = malloc_thing(pubkey_t);
1112
1113 zero(p);
1114 p->id = empty_id; /* don't know, doesn't matter */
1115 p->issuer = chunk_empty;
1116 p->serial = chunk_empty;
1117 p->public_key = key;
1118
1119 /* note that we return a 1 reference count upon creation:
1120 * invariant: recount > 0.
1121 */
1122 p->refcnt = 1;
1123 time(&p->installed_time);
1124 return p;
1125 }
1126
1127 /* Free a public key record.
1128 * As a convenience, this returns a pointer to next.
1129 */
1130 pubkey_list_t* free_public_keyentry(pubkey_list_t *p)
1131 {
1132 pubkey_list_t *nxt = p->next;
1133
1134 if (p->key != NULL)
1135 {
1136 unreference_key(&p->key);
1137 }
1138 free(p);
1139 return nxt;
1140 }
1141
1142 void free_public_keys(pubkey_list_t **keys)
1143 {
1144 while (*keys != NULL)
1145 {
1146 *keys = free_public_keyentry(*keys);
1147 }
1148 }
1149
1150 /* root of chained public key list */
1151
1152 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1153
1154 void free_remembered_public_keys(void)
1155 {
1156 free_public_keys(&pubkeys);
1157 }
1158
1159 /**
1160 * Transfer public keys from *keys list to front of pubkeys list
1161 */
1162 void transfer_to_public_keys(struct gw_info *gateways_from_dns
1163 #ifdef USE_KEYRR
1164 , pubkey_list_t **keys
1165 #endif /* USE_KEYRR */
1166 )
1167 {
1168 {
1169 struct gw_info *gwp;
1170
1171 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1172 {
1173 pubkey_list_t *pl = malloc_thing(pubkey_list_t);
1174
1175 pl->key = gwp->key; /* note: this is a transfer */
1176 gwp->key = NULL; /* really, it is! */
1177 pl->next = pubkeys;
1178 pubkeys = pl;
1179 }
1180 }
1181
1182 #ifdef USE_KEYRR
1183 {
1184 pubkey_list_t **pp = keys;
1185
1186 while (*pp != NULL)
1187 {
1188 pp = &(*pp)->next;
1189 }
1190 *pp = pubkeys;
1191 pubkeys = *keys;
1192 *keys = NULL;
1193 }
1194 #endif /* USE_KEYRR */
1195 }
1196
1197
1198 static void install_public_key(pubkey_t *pk, pubkey_list_t **head)
1199 {
1200 pubkey_list_t *p = malloc_thing(pubkey_list_t);
1201
1202 unshare_id_content(&pk->id);
1203
1204 /* copy issuer dn */
1205 pk->issuer = chunk_clone(pk->issuer);
1206
1207 /* copy serial number */
1208 pk->serial = chunk_clone(pk->serial);
1209
1210 /* store the time the public key was installed */
1211 time(&pk->installed_time);
1212
1213 /* install new key at front */
1214 p->key = reference_key(pk);
1215 p->next = *head;
1216 *head = p;
1217 }
1218
1219 void delete_public_keys(const struct id *id, key_type_t type,
1220 chunk_t issuer, chunk_t serial)
1221 {
1222 pubkey_list_t **pp, *p;
1223 pubkey_t *pk;
1224 key_type_t pk_type;
1225
1226 for (pp = &pubkeys; (p = *pp) != NULL; )
1227 {
1228 pk = p->key;
1229 pk_type = pk->public_key->get_type(pk->public_key);
1230
1231 if (same_id(id, &pk->id) && pk_type == type
1232 && (issuer.ptr == NULL || pk->issuer.ptr == NULL
1233 || same_dn(issuer, pk->issuer))
1234 && same_serial(serial, pk->serial))
1235 {
1236 *pp = free_public_keyentry(p);
1237 }
1238 else
1239 {
1240 pp = &p->next;
1241 }
1242 }
1243 }
1244
1245 pubkey_t* reference_key(pubkey_t *pk)
1246 {
1247 pk->refcnt++;
1248 return pk;
1249 }
1250
1251 void
1252 unreference_key(pubkey_t **pkp)
1253 {
1254 pubkey_t *pk = *pkp;
1255 char b[BUF_LEN];
1256
1257 if (pk == NULL)
1258 {
1259 return;
1260 }
1261
1262 /* print stuff */
1263 DBG(DBG_CONTROLMORE,
1264 idtoa(&pk->id, b, sizeof(b));
1265 DBG_log("unreference key: %p %s cnt %d--", pk, b, pk->refcnt)
1266 )
1267
1268 /* cancel out the pointer */
1269 *pkp = NULL;
1270
1271 passert(pk->refcnt != 0);
1272 pk->refcnt--;
1273 if (pk->refcnt == 0)
1274 {
1275 free_public_key(pk);
1276 }
1277 }
1278
1279 bool add_public_key(const struct id *id, enum dns_auth_level dns_auth_level,
1280 enum pubkey_alg alg, chunk_t rfc3110_key,
1281 pubkey_list_t **head)
1282 {
1283 public_key_t *key = NULL;
1284 pubkey_t *pk;
1285
1286 /* first: algorithm-specific decoding of key chunk */
1287 switch (alg)
1288 {
1289 case PUBKEY_ALG_RSA:
1290 key = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
1291 BUILD_BLOB_DNSKEY, rfc3110_key,
1292 BUILD_END);
1293 if (key == NULL)
1294 {
1295 return FALSE;
1296 }
1297 break;
1298 default:
1299 bad_case(alg);
1300 }
1301
1302 pk = malloc_thing(pubkey_t);
1303 zero(pk);
1304 pk->public_key = key;
1305 pk->id = *id;
1306 pk->dns_auth_level = dns_auth_level;
1307 pk->until_time = UNDEFINED_TIME;
1308 pk->issuer = chunk_empty;
1309 pk->serial = chunk_empty;
1310 install_public_key(pk, head);
1311 return TRUE;
1312 }
1313
1314 /* extract id and public key from x.509 certificate and
1315 * insert it into a pubkeyrec
1316 */
1317 void add_x509_public_key(x509cert_t *cert , time_t until,
1318 enum dns_auth_level dns_auth_level)
1319 {
1320 generalName_t *gn;
1321 pubkey_t *pk;
1322 key_type_t pk_type;
1323
1324 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1325 pk = malloc_thing(pubkey_t);
1326 zero(pk);
1327 pk->public_key = cert->public_key->get_ref(cert->public_key);
1328 pk->id.kind = ID_DER_ASN1_DN;
1329 pk->id.name = cert->subject;
1330 pk->dns_auth_level = dns_auth_level;
1331 pk->until_time = until;
1332 pk->issuer = cert->issuer;
1333 pk->serial = cert->serialNumber;
1334 pk_type = pk->public_key->get_type(pk->public_key);
1335 delete_public_keys(&pk->id, pk_type, pk->issuer, pk->serial);
1336 install_public_key(pk, &pubkeys);
1337
1338 gn = cert->subjectAltName;
1339
1340 while (gn != NULL) /* insert all subjectAltNames */
1341 {
1342 struct id id = empty_id;
1343
1344 gntoid(&id, gn);
1345 if (id.kind != ID_ANY)
1346 {
1347 pk = malloc_thing(pubkey_t);
1348 zero(pk);
1349 pk->public_key = cert->public_key->get_ref(cert->public_key);
1350 pk->id = id;
1351 pk->dns_auth_level = dns_auth_level;
1352 pk->until_time = until;
1353 pk->issuer = cert->issuer;
1354 pk->serial = cert->serialNumber;
1355 delete_public_keys(&pk->id, pk_type, pk->issuer, pk->serial);
1356 install_public_key(pk, &pubkeys);
1357 }
1358 gn = gn->next;
1359 }
1360 }
1361
1362 /* extract id and public key from OpenPGP certificate and
1363 * insert it into a pubkeyrec
1364 */
1365 void add_pgp_public_key(pgpcert_t *cert , time_t until,
1366 enum dns_auth_level dns_auth_level)
1367 {
1368 pubkey_t *pk;
1369 key_type_t pk_type;
1370
1371 pk = malloc_thing(pubkey_t);
1372 zero(pk);
1373 pk->public_key = cert->public_key->get_ref(cert->public_key);
1374 pk->id.kind = ID_KEY_ID;
1375 pk->id.name = cert->fingerprint->get_encoding(cert->fingerprint);
1376 pk->dns_auth_level = dns_auth_level;
1377 pk->until_time = until;
1378 pk_type = pk->public_key->get_type(pk->public_key);
1379 delete_public_keys(&pk->id, pk_type, chunk_empty, chunk_empty);
1380 install_public_key(pk, &pubkeys);
1381 }
1382
1383 /* when a X.509 certificate gets revoked, all instances of
1384 * the corresponding public key must be removed
1385 */
1386 void remove_x509_public_key(const x509cert_t *cert)
1387 {
1388 public_key_t *revoked_key = cert->public_key;
1389 pubkey_list_t *p, **pp;
1390
1391 p = pubkeys;
1392 pp = &pubkeys;
1393
1394 while(p != NULL)
1395 {
1396 if (revoked_key->equals(revoked_key, p->key->public_key))
1397 {
1398 /* remove p from list and free memory */
1399 *pp = free_public_keyentry(p);
1400 loglog(RC_LOG_SERIOUS, "invalid public key deleted");
1401 }
1402 else
1403 {
1404 pp = &p->next;
1405 }
1406 p =*pp;
1407 }
1408 }
1409
1410 /*
1411 * list all public keys in the chained list
1412 */
1413 void list_public_keys(bool utc)
1414 {
1415 pubkey_list_t *p = pubkeys;
1416
1417 if (p != NULL)
1418 {
1419 whack_log(RC_COMMENT, " ");
1420 whack_log(RC_COMMENT, "List of Public Keys:");
1421 whack_log(RC_COMMENT, " ");
1422 }
1423
1424 while (p != NULL)
1425 {
1426 pubkey_t *key = p->key;
1427 public_key_t *public = key->public_key;
1428 chunk_t keyid;
1429 char buf[BUF_LEN];
1430
1431 idtoa(&key->id, buf, BUF_LEN);
1432 whack_log(RC_COMMENT,"%T, '%s'", &key->installed_time, utc, buf);
1433 whack_log(RC_COMMENT, " pubkey: %N %4d bits, until %T %s",
1434 key_type_names, public->get_type(public),
1435 public->get_keysize(public) * BITS_PER_BYTE,
1436 &key->until_time, utc,
1437 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1438 if (public->get_fingerprint(public, KEY_ID_PUBKEY_INFO_SHA1, &keyid))
1439 {
1440 whack_log(RC_COMMENT," keyid: %#B", &keyid);
1441 }
1442 if (key->issuer.len > 0)
1443 {
1444 dntoa(buf, BUF_LEN, key->issuer);
1445 whack_log(RC_COMMENT," issuer: '%s'", buf);
1446 }
1447 if (key->serial.len > 0)
1448 {
1449 datatot(key->serial.ptr, key->serial.len, ':'
1450 , buf, BUF_LEN);
1451 whack_log(RC_COMMENT," serial: %s", buf);
1452 }
1453 p = p->next;
1454 }
1455 }