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