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