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