debug info on preshared secrets
[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 #include "xauth.h"
58
59 const char *shared_secrets_file = SHARED_SECRETS_FILE;
60
61 typedef struct id_list id_list_t;
62
63 struct id_list {
64 struct id id;
65 id_list_t *next;
66 };
67
68 typedef struct secret secret_t;
69
70 struct secret {
71 id_list_t *ids;
72 enum PrivateKeyKind kind;
73 union {
74 chunk_t preshared_secret;
75 RSA_private_key_t RSA_private_key;
76 xauth_t xauth_secret;
77 smartcard_t *smartcard;
78 } u;
79 secret_t *next;
80 };
81
82 static pubkey_t*
83 allocate_RSA_public_key(const cert_t cert)
84 {
85 pubkey_t *pk = alloc_thing(pubkey_t, "pubkey");
86 chunk_t e, n;
87
88 switch (cert.type)
89 {
90 case CERT_PGP:
91 e = cert.u.pgp->publicExponent;
92 n = cert.u.pgp->modulus;
93 break;
94 case CERT_X509_SIGNATURE:
95 e = cert.u.x509->publicExponent;
96 n = cert.u.x509->modulus;
97 break;
98 default:
99 plog("RSA public key allocation error");
100 }
101
102 init_RSA_public_key(&pk->u.rsa, e, n);
103 DBG(DBG_RAW,
104 RSA_show_public_key(&pk->u.rsa)
105 )
106
107 pk->alg = PUBKEY_ALG_RSA;
108 pk->id = empty_id;
109 pk->issuer = empty_chunk;
110 pk->serial = empty_chunk;
111
112 return pk;
113 }
114
115 /*
116 * free a public key struct
117 */
118 static void
119 free_public_key(pubkey_t *pk)
120 {
121 free_id_content(&pk->id);
122 freeanychunk(pk->issuer);
123 freeanychunk(pk->serial);
124
125 /* algorithm-specific freeing */
126 switch (pk->alg)
127 {
128 case PUBKEY_ALG_RSA:
129 free_RSA_public_content(&pk->u.rsa);
130 break;
131 default:
132 bad_case(pk->alg);
133 }
134 pfree(pk);
135 }
136
137 secret_t *secrets = NULL;
138
139 /* find the struct secret associated with the combination of
140 * me and the peer. We match the Id (if none, the IP address).
141 * Failure is indicated by a NULL.
142 */
143 static const secret_t *
144 get_secret(const struct connection *c, enum PrivateKeyKind kind, bool asym)
145 {
146 enum { /* bits */
147 match_default = 01,
148 match_him = 02,
149 match_me = 04
150 };
151
152 unsigned int best_match = 0;
153 secret_t *best = NULL;
154 secret_t *s;
155 const struct id *my_id = &c->spd.this.id
156 , *his_id = &c->spd.that.id;
157 struct id rw_id;
158
159 /* is there a certificate assigned to this connection? */
160 if (kind == PPK_RSA && c->spd.this.cert.type != CERT_NONE)
161 {
162 pubkey_t *my_public_key = allocate_RSA_public_key(c->spd.this.cert);
163
164 for (s = secrets; s != NULL; s = s->next)
165 {
166 if (s->kind == kind &&
167 same_RSA_public_key(&s->u.RSA_private_key.pub, &my_public_key->u.rsa))
168 {
169 best = s;
170 break; /* we have found the private key - no sense in searching further */
171 }
172 }
173 free_public_key(my_public_key);
174 return best;
175 }
176
177 if (his_id_was_instantiated(c))
178 {
179 /* roadwarrior: replace him with 0.0.0.0 */
180 rw_id.kind = c->spd.that.id.kind;
181 rw_id.name = empty_chunk;
182 happy(anyaddr(addrtypeof(&c->spd.that.host_addr), &rw_id.ip_addr));
183 his_id = &rw_id;
184 }
185 else if (kind == PPK_PSK
186 && (c->policy & (POLICY_PSK | POLICY_XAUTH_PSK))
187 && ((c->kind == CK_TEMPLATE && c->spd.that.id.kind == ID_NONE) ||
188 (c->kind == CK_INSTANCE && id_is_ipaddr(&c->spd.that.id))))
189 {
190 /* roadwarrior: replace him with 0.0.0.0 */
191 rw_id.kind = ID_IPV4_ADDR;
192 happy(anyaddr(addrtypeof(&c->spd.that.host_addr), &rw_id.ip_addr));
193 his_id = &rw_id;
194 }
195
196 for (s = secrets; s != NULL; s = s->next)
197 {
198 if (s->kind == kind)
199 {
200 unsigned int match = 0;
201
202 if (s->ids == NULL)
203 {
204 /* a default (signified by lack of ids):
205 * accept if no more specific match found
206 */
207 match = match_default;
208 }
209 else
210 {
211 /* check if both ends match ids */
212 id_list_t *i;
213
214 for (i = s->ids; i != NULL; i = i->next)
215 {
216 if (same_id(my_id, &i->id))
217 match |= match_me;
218
219 if (same_id(his_id, &i->id))
220 match |= match_him;
221 }
222
223 /* If our end matched the only id in the list,
224 * default to matching any peer.
225 * A more specific match will trump this.
226 */
227 if (match == match_me
228 && s->ids->next == NULL)
229 match |= match_default;
230 }
231
232 switch (match)
233 {
234 case match_me:
235 /* if this is an asymmetric (eg. public key) system,
236 * allow this-side-only match to count, even if
237 * there are other ids in the list.
238 */
239 if (!asym)
240 break;
241 /* FALLTHROUGH */
242 case match_default: /* default all */
243 case match_me | match_default: /* default peer */
244 case match_me | match_him: /* explicit */
245 if (match == best_match)
246 {
247 /* two good matches are equally good:
248 * do they agree?
249 */
250 bool same = FALSE;
251
252 switch (kind)
253 {
254 case PPK_PSK:
255 same = s->u.preshared_secret.len == best->u.preshared_secret.len
256 && memcmp(s->u.preshared_secret.ptr, best->u.preshared_secret.ptr, s->u.preshared_secret.len) == 0;
257 break;
258 case PPK_RSA:
259 /* Dirty trick: since we have code to compare
260 * RSA public keys, but not private keys, we
261 * make the assumption that equal public keys
262 * mean equal private keys. This ought to work.
263 */
264 same = same_RSA_public_key(&s->u.RSA_private_key.pub
265 , &best->u.RSA_private_key.pub);
266 break;
267 default:
268 bad_case(kind);
269 }
270 if (!same)
271 {
272 loglog(RC_LOG_SERIOUS, "multiple ipsec.secrets entries with distinct secrets match endpoints:"
273 " first secret used");
274 best = s; /* list is backwards: take latest in list */
275 }
276 }
277 else if (match > best_match)
278 {
279 /* this is the best match so far */
280 best_match = match;
281 best = s;
282 }
283 }
284 }
285 }
286 return best;
287 }
288
289 /* find the appropriate preshared key (see get_secret).
290 * Failure is indicated by a NULL pointer.
291 * Note: the result is not to be freed by the caller.
292 */
293 const chunk_t *
294 get_preshared_secret(const struct connection *c)
295 {
296 const secret_t *s = get_secret(c, PPK_PSK, FALSE);
297
298 DBG(DBG_PRIVATE,
299 if (s == NULL)
300 DBG_log("no Preshared Key Found");
301 else
302 DBG_dump_chunk("Preshared Key", s->u.preshared_secret);
303 )
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[BUF_LEN]; /* 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 xauth secret read from ipsec.secrets
588 */
589 static err_t
590 process_xauth(secret_t *s)
591 {
592 chunk_t user_name;
593
594 s->kind = PPK_XAUTH;
595
596 if (!shift())
597 return "missing xauth user name";
598 if (*tok == '"' || *tok == '\'') /* quoted user name */
599 {
600 user_name.ptr = tok + 1;
601 user_name.len = flp->cur - tok - 2;
602 }
603 else
604 {
605 user_name.ptr = tok;
606 user_name.len = flp->cur - tok;
607 }
608 plog(" loaded xauth credentials of user '%.*s'"
609 , user_name.len
610 , user_name.ptr);
611 clonetochunk(s->u.xauth_secret.user_name
612 , user_name.ptr, user_name.len, "xauth user name");
613
614 if (!shift())
615 return "missing xauth user password";
616 return process_psk_secret(&s->u.xauth_secret.user_password);
617 }
618
619 /* get XAUTH secret from chained secrets lists
620 * only one entry is currently supported
621 */
622 static bool
623 xauth_get_secret(xauth_t *xauth_secret)
624 {
625 secret_t *s;
626 bool found = FALSE;
627
628 for (s = secrets; s != NULL; s = s->next)
629 {
630 if (s->kind == PPK_XAUTH)
631 {
632 if (found)
633 {
634 plog("found multiple xauth secrets - first selected");
635 }
636 else
637 {
638 found = TRUE;
639 *xauth_secret = s->u.xauth_secret;
640 }
641 }
642 }
643 return found;
644 }
645
646 /*
647 * find a matching secret
648 */
649 static bool
650 xauth_verify_secret(const char *conn_name, const xauth_t *xauth_secret)
651 {
652 bool found = FALSE;
653 secret_t *s;
654
655 for (s = secrets; s != NULL; s = s->next)
656 {
657 if (s->kind == PPK_XAUTH)
658 {
659 if (!same_chunk(xauth_secret->user_name, s->u.xauth_secret.user_name))
660 continue;
661 found = TRUE;
662 if (same_chunk(xauth_secret->user_password, s->u.xauth_secret.user_password))
663 return TRUE;
664 }
665 }
666 plog("xauth user '%.*s' %s"
667 , xauth_secret->user_name.len, xauth_secret->user_name.ptr
668 , found? "sent wrong password":"not found");
669 return FALSE;
670 }
671
672 /*
673 * the global xauth_module struct is defined here
674 */
675 xauth_module_t xauth_module;
676
677 /*
678 * assign the default xauth functions to any null function pointers
679 */
680 void
681 xauth_defaults(void)
682 {
683 if (xauth_module.get_secret == NULL)
684 {
685 DBG(DBG_CONTROL,
686 DBG_log("xauth module: using default get_secret() function")
687 )
688 xauth_module.get_secret = xauth_get_secret;
689 }
690 if (xauth_module.verify_secret == NULL)
691 {
692 DBG(DBG_CONTROL,
693 DBG_log("xauth module: using default verify_secret() function")
694 )
695 xauth_module.verify_secret = xauth_verify_secret;
696 }
697 };
698
699 /*
700 * process pin read from ipsec.secrets or prompted for it using whack
701 */
702 static err_t
703 process_pin(secret_t *s, int whackfd)
704 {
705 smartcard_t *sc;
706 const char *pin_status = "no pin";
707
708 s->kind = PPK_PIN;
709
710 /* looking for the smartcard keyword */
711 if (!shift() || strncmp(tok, SCX_TOKEN, strlen(SCX_TOKEN)) != 0)
712 return "PIN keyword must be followed by %smartcard<reader>:<id>";
713
714 sc = scx_add(scx_parse_number_slot_id(tok + strlen(SCX_TOKEN)));
715 s->u.smartcard = sc;
716 scx_share(sc);
717 if (sc->pin.ptr != NULL)
718 {
719 scx_release_context(sc);
720 scx_free_pin(&sc->pin);
721 }
722 sc->valid = FALSE;
723
724 if (!shift())
725 return "PIN statement must be terminated either by <pin code>, %pinpad or %prompt";
726
727 if (tokeqword("%prompt"))
728 {
729 shift();
730 /* if whackfd exists, whack will be used to prompt for a pin */
731 if (whackfd != NULL_FD)
732 pin_status = scx_get_pin(sc, whackfd) ? "valid pin" : "invalid pin";
733 else
734 pin_status = "pin entry via prompt";
735 }
736 else if (tokeqword("%pinpad"))
737 {
738 shift();
739 /* pin will be entered via pin pad during verification */
740 clonetochunk(sc->pin, "", 0, "empty pin");
741 sc->pinpad = TRUE;
742 sc->valid = TRUE;
743 pin_status = "pin entry via pad";
744 if (pkcs11_keep_state)
745 scx_verify_pin(sc);
746 }
747 else
748 {
749 /* we read the pin directly from ipsec.secrets */
750 err_t ugh = process_psk_secret(&sc->pin);
751 if (ugh != NULL)
752 return ugh;
753 /* verify the pin */
754 pin_status = scx_verify_pin(sc) ? "valid PIN" : "invalid PIN";
755 }
756 #ifdef SMARTCARD
757 {
758 char buf[BUF_LEN];
759
760 if (sc->any_slot)
761 snprintf(buf, BUF_LEN, "any slot");
762 else
763 snprintf(buf, BUF_LEN, "slot: %lu", sc->slot);
764
765 plog(" %s for #%d (%s, id: %s)"
766 , pin_status, sc->number, scx_print_slot(sc, ""), sc->id);
767 }
768 #else
769 plog(" warning: SMARTCARD support is deactivated in pluto/Makefile!");
770 #endif
771 return NULL;
772 }
773
774 static void
775 log_psk(secret_t *s)
776 {
777 int n = 0;
778 char buf[BUF_LEN];
779 id_list_t *id_list = s->ids;
780
781 if (id_list == NULL)
782 {
783 n = snprintf(buf, BUF_LEN, "%%any");
784 }
785 else
786 {
787 do
788 {
789 n += idtoa(&id_list->id, buf + n, BUF_LEN - n);
790 if (n >= BUF_LEN)
791 {
792 n = BUF_LEN - 1;
793 break;
794 }
795 id_list = id_list->next;
796 }
797 while (id_list);
798 }
799 plog(" loaded shared key for %.*s", n, buf);
800 }
801
802 static void
803 process_secret(secret_t *s, int whackfd)
804 {
805 err_t ugh = NULL;
806
807 s->kind = PPK_PSK; /* default */
808 if (*tok == '"' || *tok == '\'')
809 {
810 /* old PSK format: just a string */
811 log_psk(s);
812 ugh = process_psk_secret(&s->u.preshared_secret);
813 }
814 else if (tokeqword("psk"))
815 {
816 /* preshared key: quoted string or ttodata format */
817 log_psk(s);
818 ugh = !shift()? "unexpected end of record in PSK"
819 : process_psk_secret(&s->u.preshared_secret);
820 }
821 else if (tokeqword("rsa"))
822 {
823 /* RSA key: the fun begins.
824 * A braced list of keyword and value pairs.
825 */
826 s->kind = PPK_RSA;
827 if (!shift())
828 {
829 ugh = "bad RSA key syntax";
830 }
831 else if (tokeq("{"))
832 {
833 ugh = process_rsa_secret(&s->u.RSA_private_key);
834 }
835 else
836 {
837 ugh = process_rsa_keyfile(&s->u.RSA_private_key, whackfd);
838 }
839 }
840 else if (tokeqword("xauth"))
841 {
842 ugh = process_xauth(s);
843 }
844 else if (tokeqword("pin"))
845 {
846 ugh = process_pin(s, whackfd);
847 }
848 else
849 {
850 ugh = builddiag("unrecognized key format: %s", tok);
851 }
852
853 if (ugh != NULL)
854 {
855 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
856 , flp->filename, flp->lino, ugh);
857 pfree(s);
858 }
859 else if (flushline("expected record boundary in key"))
860 {
861 /* gauntlet has been run: install new secret */
862 lock_certs_and_keys("process_secret");
863 s->next = secrets;
864 secrets = s;
865 unlock_certs_and_keys("process_secrets");
866 }
867 }
868
869 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
870
871 static void
872 process_secret_records(int whackfd)
873 {
874 /* read records from ipsec.secrets and load them into our table */
875 for (;;)
876 {
877 (void)flushline(NULL); /* silently ditch leftovers, if any */
878 if (flp->bdry == B_file)
879 break;
880
881 flp->bdry = B_none; /* eat the Record Boundary */
882 (void)shift(); /* get real first token */
883
884 if (tokeqword("include"))
885 {
886 /* an include directive */
887 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
888 char *p = fn;
889 char *end_prefix = strrchr(flp->filename, '/');
890
891 if (!shift())
892 {
893 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
894 , flp->filename, flp->lino);
895 continue; /* abandon this record */
896 }
897
898 /* if path is relative and including file's pathname has
899 * a non-empty dirname, prefix this path with that dirname.
900 */
901 if (tok[0] != '/' && end_prefix != NULL)
902 {
903 size_t pl = end_prefix - flp->filename + 1;
904
905 /* "clamp" length to prevent problems now;
906 * will be rediscovered and reported later.
907 */
908 if (pl > sizeof(fn))
909 pl = sizeof(fn);
910 memcpy(fn, flp->filename, pl);
911 p += pl;
912 }
913 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
914 {
915 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
916 , flp->filename, flp->lino);
917 continue; /* abandon this record */
918 }
919 strcpy(p, tok);
920 (void) shift(); /* move to Record Boundary, we hope */
921 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
922 {
923 process_secrets_file(fn, whackfd);
924 tok = NULL; /* correct, but probably redundant */
925 }
926 }
927 else
928 {
929 /* expecting a list of indices and then the key info */
930 secret_t *s = alloc_thing(secret_t, "secret");
931
932 s->ids = NULL;
933 s->kind = PPK_PSK; /* default */
934 setchunk(s->u.preshared_secret, NULL, 0);
935 s->next = NULL;
936
937 for (;;)
938 {
939 if (tok[0] == '"' || tok[0] == '\'')
940 {
941 /* found key part */
942 process_secret(s, whackfd);
943 break;
944 }
945 else if (tokeq(":"))
946 {
947 /* found key part */
948 shift(); /* discard explicit separator */
949 process_secret(s, whackfd);
950 break;
951 }
952 else
953 {
954 /* an id
955 * See RFC2407 IPsec Domain of Interpretation 4.6.2
956 */
957 struct id id;
958 err_t ugh;
959
960 if (tokeq("%any"))
961 {
962 id = empty_id;
963 id.kind = ID_IPV4_ADDR;
964 ugh = anyaddr(AF_INET, &id.ip_addr);
965 }
966 else if (tokeq("%any6"))
967 {
968 id = empty_id;
969 id.kind = ID_IPV6_ADDR;
970 ugh = anyaddr(AF_INET6, &id.ip_addr);
971 }
972 else
973 {
974 ugh = atoid(tok, &id, FALSE);
975 }
976
977 if (ugh != NULL)
978 {
979 loglog(RC_LOG_SERIOUS
980 , "ERROR \"%s\" line %d: index \"%s\" %s"
981 , flp->filename, flp->lino, tok, ugh);
982 }
983 else
984 {
985 id_list_t *i = alloc_thing(id_list_t
986 , "id_list");
987
988 i->id = id;
989 unshare_id_content(&i->id);
990 i->next = s->ids;
991 s->ids = i;
992 /* DBG_log("id type %d: %s %.*s", i->kind, ip_str(&i->ip_addr), (int)i->name.len, i->name.ptr); */
993 }
994 if (!shift())
995 {
996 /* unexpected Record Boundary or EOF */
997 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of id list"
998 , flp->filename, flp->lino);
999 break;
1000 }
1001 }
1002 }
1003 }
1004 }
1005 }
1006
1007 static int
1008 globugh(const char *epath, int eerrno)
1009 {
1010 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
1011 return 1; /* stop glob */
1012 }
1013
1014 static void
1015 process_secrets_file(const char *file_pat, int whackfd)
1016 {
1017 struct file_lex_position pos;
1018 char **fnp;
1019 glob_t globbuf;
1020
1021 pos.depth = flp == NULL? 0 : flp->depth + 1;
1022
1023 if (pos.depth > 10)
1024 {
1025 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
1026 return;
1027 }
1028
1029 /* do globbing */
1030 {
1031 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1032
1033 if (r != 0)
1034 {
1035 switch (r)
1036 {
1037 case GLOB_NOSPACE:
1038 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1039 break;
1040 case GLOB_ABORTED:
1041 break; /* already logged */
1042 case GLOB_NOMATCH:
1043 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1044 break;
1045 default:
1046 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1047 break;
1048 }
1049 globfree(&globbuf);
1050 return;
1051 }
1052 }
1053
1054 /* for each file... */
1055 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1056 {
1057 if (lexopen(&pos, *fnp, FALSE))
1058 {
1059 plog("loading secrets from \"%s\"", *fnp);
1060 (void) flushline("file starts with indentation (continuation notation)");
1061 process_secret_records(whackfd);
1062 lexclose();
1063 }
1064 }
1065
1066 globfree(&globbuf);
1067 }
1068
1069 void
1070 free_preshared_secrets(void)
1071 {
1072 lock_certs_and_keys("free_preshared_secrets");
1073
1074 if (secrets != NULL)
1075 {
1076 secret_t *s, *ns;
1077
1078 plog("forgetting secrets");
1079
1080 for (s = secrets; s != NULL; s = ns)
1081 {
1082 id_list_t *i, *ni;
1083
1084 ns = s->next; /* grab before freeing s */
1085 for (i = s->ids; i != NULL; i = ni)
1086 {
1087 ni = i->next; /* grab before freeing i */
1088 free_id_content(&i->id);
1089 pfree(i);
1090 }
1091 switch (s->kind)
1092 {
1093 case PPK_PSK:
1094 pfree(s->u.preshared_secret.ptr);
1095 break;
1096 case PPK_RSA:
1097 free_RSA_private_content(&s->u.RSA_private_key);
1098 break;
1099 case PPK_XAUTH:
1100 pfree(s->u.xauth_secret.user_name.ptr);
1101 pfree(s->u.xauth_secret.user_password.ptr);
1102 break;
1103 case PPK_PIN:
1104 scx_release(s->u.smartcard);
1105 break;
1106 default:
1107 bad_case(s->kind);
1108 }
1109 pfree(s);
1110 }
1111 secrets = NULL;
1112 }
1113
1114 unlock_certs_and_keys("free_preshard_secrets");
1115 }
1116
1117 void
1118 load_preshared_secrets(int whackfd)
1119 {
1120 free_preshared_secrets();
1121 (void) process_secrets_file(shared_secrets_file, whackfd);
1122 }
1123
1124 /* public key machinery
1125 * Note: caller must set dns_auth_level.
1126 */
1127
1128 pubkey_t *
1129 public_key_from_rsa(const RSA_public_key_t *k)
1130 {
1131 pubkey_t *p = alloc_thing(pubkey_t, "pubkey");
1132
1133 p->id = empty_id; /* don't know, doesn't matter */
1134 p->issuer = empty_chunk;
1135 p->serial = empty_chunk;
1136 p->alg = PUBKEY_ALG_RSA;
1137
1138 memcpy(p->u.rsa.keyid, k->keyid, sizeof(p->u.rsa.keyid));
1139 p->u.rsa.k = k->k;
1140 mpz_init_set(&p->u.rsa.e, &k->e);
1141 mpz_init_set(&p->u.rsa.n, &k->n);
1142
1143 /* note that we return a 1 reference count upon creation:
1144 * invariant: recount > 0.
1145 */
1146 p->refcnt = 1;
1147 time(&p->installed_time);
1148 return p;
1149 }
1150
1151 /* Free a public key record.
1152 * As a convenience, this returns a pointer to next.
1153 */
1154 pubkey_list_t *
1155 free_public_keyentry(pubkey_list_t *p)
1156 {
1157 pubkey_list_t *nxt = p->next;
1158
1159 if (p->key != NULL)
1160 unreference_key(&p->key);
1161 pfree(p);
1162 return nxt;
1163 }
1164
1165 void
1166 free_public_keys(pubkey_list_t **keys)
1167 {
1168 while (*keys != NULL)
1169 *keys = free_public_keyentry(*keys);
1170 }
1171
1172 /* root of chained public key list */
1173
1174 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1175
1176 void
1177 free_remembered_public_keys(void)
1178 {
1179 free_public_keys(&pubkeys);
1180 }
1181
1182 /* transfer public keys from *keys list to front of pubkeys list */
1183 void
1184 transfer_to_public_keys(struct gw_info *gateways_from_dns
1185 #ifdef USE_KEYRR
1186 , pubkey_list_t **keys
1187 #endif /* USE_KEYRR */
1188 )
1189 {
1190 {
1191 struct gw_info *gwp;
1192
1193 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1194 {
1195 pubkey_list_t *pl = alloc_thing(pubkey_list_t, "from TXT");
1196
1197 pl->key = gwp->key; /* note: this is a transfer */
1198 gwp->key = NULL; /* really, it is! */
1199 pl->next = pubkeys;
1200 pubkeys = pl;
1201 }
1202 }
1203
1204 #ifdef USE_KEYRR
1205 {
1206 pubkey_list_t **pp = keys;
1207
1208 while (*pp != NULL)
1209 pp = &(*pp)->next;
1210 *pp = pubkeys;
1211 pubkeys = *keys;
1212 *keys = NULL;
1213 }
1214 #endif /* USE_KEYRR */
1215 }
1216
1217 /* decode of RSA pubkey chunk
1218 * - format specified in RFC 2537 RSA/MD5 Keys and SIGs in the DNS
1219 * - exponent length in bytes (1 or 3 octets)
1220 * + 1 byte if in [1, 255]
1221 * + otherwise 0x00 followed by 2 bytes of length
1222 * - exponent
1223 * - modulus
1224 */
1225 err_t
1226 unpack_RSA_public_key(RSA_public_key_t *rsa, const chunk_t *pubkey)
1227 {
1228 chunk_t exp;
1229 chunk_t mod;
1230
1231 if (pubkey->len < 3)
1232 return "RSA public key blob way to short"; /* not even room for length! */
1233
1234 if (pubkey->ptr[0] != 0x00)
1235 {
1236 setchunk(exp, pubkey->ptr + 1, pubkey->ptr[0]);
1237 }
1238 else
1239 {
1240 setchunk(exp, pubkey->ptr + 3
1241 , (pubkey->ptr[1] << BITS_PER_BYTE) + pubkey->ptr[2]);
1242 }
1243
1244 if (pubkey->len - (exp.ptr - pubkey->ptr) < exp.len + RSA_MIN_OCTETS_RFC)
1245 return "RSA public key blob too short";
1246
1247 mod.ptr = exp.ptr + exp.len;
1248 mod.len = &pubkey->ptr[pubkey->len] - mod.ptr;
1249
1250 if (mod.len < RSA_MIN_OCTETS)
1251 return RSA_MIN_OCTETS_UGH;
1252
1253 if (mod.len > RSA_MAX_OCTETS)
1254 return RSA_MAX_OCTETS_UGH;
1255
1256 init_RSA_public_key(rsa, exp, mod);
1257 rsa->k = mpz_sizeinbase(&rsa->n, 2); /* size in bits, for a start */
1258 rsa->k = (rsa->k + BITS_PER_BYTE - 1) / BITS_PER_BYTE; /* now octets */
1259 DBG(DBG_RAW,
1260 RSA_show_public_key(rsa)
1261 )
1262
1263 if (rsa->k != mod.len)
1264 {
1265 mpz_clear(&rsa->e);
1266 mpz_clear(&rsa->n);
1267 return "RSA modulus shorter than specified";
1268 }
1269
1270 return NULL;
1271 }
1272
1273 static void
1274 install_public_key(pubkey_t *pk, pubkey_list_t **head)
1275 {
1276 pubkey_list_t *p = alloc_thing(pubkey_list_t, "pubkey entry");
1277
1278 unshare_id_content(&pk->id);
1279
1280 /* copy issuer dn */
1281 if (pk->issuer.ptr != NULL)
1282 pk->issuer.ptr = clone_bytes(pk->issuer.ptr, pk->issuer.len, "issuer dn");
1283
1284 /* copy serial number */
1285 if (pk->serial.ptr != NULL)
1286 pk->serial.ptr = clone_bytes(pk->serial.ptr, pk->serial.len, "serialNumber");
1287
1288 /* store the time the public key was installed */
1289 time(&pk->installed_time);
1290
1291 /* install new key at front */
1292 p->key = reference_key(pk);
1293 p->next = *head;
1294 *head = p;
1295 }
1296
1297
1298 void
1299 delete_public_keys(const struct id *id, enum pubkey_alg alg
1300 , chunk_t issuer, chunk_t serial)
1301 {
1302 pubkey_list_t **pp, *p;
1303 pubkey_t *pk;
1304
1305 for (pp = &pubkeys; (p = *pp) != NULL; )
1306 {
1307 pk = p->key;
1308
1309 if (same_id(id, &pk->id) && pk->alg == alg
1310 && (issuer.ptr == NULL || pk->issuer.ptr == NULL
1311 || same_dn(issuer, pk->issuer))
1312 && same_serial(serial, pk->serial))
1313 *pp = free_public_keyentry(p);
1314 else
1315 pp = &p->next;
1316 }
1317 }
1318
1319 pubkey_t *
1320 reference_key(pubkey_t *pk)
1321 {
1322 pk->refcnt++;
1323 return pk;
1324 }
1325
1326 void
1327 unreference_key(pubkey_t **pkp)
1328 {
1329 pubkey_t *pk = *pkp;
1330 char b[BUF_LEN];
1331
1332 if (pk == NULL)
1333 return;
1334
1335 /* print stuff */
1336 DBG(DBG_CONTROLMORE,
1337 idtoa(&pk->id, b, sizeof(b));
1338 DBG_log("unreference key: %p %s cnt %d--", pk, b, pk->refcnt)
1339 )
1340
1341 /* cancel out the pointer */
1342 *pkp = NULL;
1343
1344 passert(pk->refcnt != 0);
1345 pk->refcnt--;
1346 if (pk->refcnt == 0)
1347 free_public_key(pk);
1348 }
1349
1350 err_t
1351 add_public_key(const struct id *id
1352 , enum dns_auth_level dns_auth_level
1353 , enum pubkey_alg alg
1354 , const chunk_t *key
1355 , pubkey_list_t **head)
1356 {
1357 pubkey_t *pk = alloc_thing(pubkey_t, "pubkey");
1358
1359 /* first: algorithm-specific decoding of key chunk */
1360 switch (alg)
1361 {
1362 case PUBKEY_ALG_RSA:
1363 {
1364 err_t ugh = unpack_RSA_public_key(&pk->u.rsa, key);
1365
1366 if (ugh != NULL)
1367 {
1368 pfree(pk);
1369 return ugh;
1370 }
1371 }
1372 break;
1373 default:
1374 bad_case(alg);
1375 }
1376
1377 pk->id = *id;
1378 pk->dns_auth_level = dns_auth_level;
1379 pk->alg = alg;
1380 pk->until_time = UNDEFINED_TIME;
1381 pk->issuer = empty_chunk;
1382 pk->serial = empty_chunk;
1383
1384 install_public_key(pk, head);
1385 return NULL;
1386 }
1387
1388 /* extract id and public key from x.509 certificate and
1389 * insert it into a pubkeyrec
1390 */
1391 void
1392 add_x509_public_key(x509cert_t *cert , time_t until
1393 , enum dns_auth_level dns_auth_level)
1394 {
1395 generalName_t *gn;
1396 pubkey_t *pk;
1397 cert_t c = { CERT_X509_SIGNATURE, {cert} };
1398
1399 /* we support RSA only */
1400 if (cert->subjectPublicKeyAlgorithm != PUBKEY_ALG_RSA)
1401 return;
1402
1403 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1404 pk = allocate_RSA_public_key(c);
1405 pk->id.kind = ID_DER_ASN1_DN;
1406 pk->id.name = cert->subject;
1407 pk->dns_auth_level = dns_auth_level;
1408 pk->until_time = until;
1409 pk->issuer = cert->issuer;
1410 pk->serial = cert->serialNumber;
1411 delete_public_keys(&pk->id, pk->alg, pk->issuer, pk->serial);
1412 install_public_key(pk, &pubkeys);
1413
1414 gn = cert->subjectAltName;
1415
1416 while (gn != NULL) /* insert all subjectAltNames */
1417 {
1418 struct id id = empty_id;
1419
1420 gntoid(&id, gn);
1421 if (id.kind != ID_NONE)
1422 {
1423 pk = allocate_RSA_public_key(c);
1424 pk->id = id;
1425 pk->dns_auth_level = dns_auth_level;
1426 pk->until_time = until;
1427 pk->issuer = cert->issuer;
1428 pk->serial = cert->serialNumber;
1429 delete_public_keys(&pk->id, pk->alg, pk->issuer, pk->serial);
1430 install_public_key(pk, &pubkeys);
1431 }
1432 gn = gn->next;
1433 }
1434 }
1435
1436 /* extract id and public key from OpenPGP certificate and
1437 * insert it into a pubkeyrec
1438 */
1439 void
1440 add_pgp_public_key(pgpcert_t *cert , time_t until
1441 , enum dns_auth_level dns_auth_level)
1442 {
1443 pubkey_t *pk;
1444 cert_t c;
1445
1446 c.type = CERT_PGP;
1447 c.u.pgp = cert;
1448
1449 /* we support RSA only */
1450 if (cert->pubkeyAlg != PUBKEY_ALG_RSA)
1451 {
1452 plog(" RSA public keys supported only");
1453 return;
1454 }
1455
1456 pk = allocate_RSA_public_key(c);
1457 pk->id.kind = ID_KEY_ID;
1458 pk->id.name.ptr = cert->fingerprint;
1459 pk->id.name.len = PGP_FINGERPRINT_SIZE;
1460 pk->dns_auth_level = dns_auth_level;
1461 pk->until_time = until;
1462 delete_public_keys(&pk->id, pk->alg, empty_chunk, empty_chunk);
1463 install_public_key(pk, &pubkeys);
1464 }
1465
1466 /* when a X.509 certificate gets revoked, all instances of
1467 * the corresponding public key must be removed
1468 */
1469 void
1470 remove_x509_public_key(const x509cert_t *cert)
1471 {
1472 const cert_t c = {CERT_X509_SIGNATURE, {cert}};
1473 pubkey_list_t *p, **pp;
1474 pubkey_t *revoked_pk;
1475
1476 revoked_pk = allocate_RSA_public_key(c);
1477 p = pubkeys;
1478 pp = &pubkeys;
1479
1480 while(p != NULL)
1481 {
1482 if (same_RSA_public_key(&p->key->u.rsa, &revoked_pk->u.rsa))
1483 {
1484 /* remove p from list and free memory */
1485 *pp = free_public_keyentry(p);
1486 loglog(RC_LOG_SERIOUS,
1487 "invalid RSA public key deleted");
1488 }
1489 else
1490 {
1491 pp = &p->next;
1492 }
1493 p =*pp;
1494 }
1495 free_public_key(revoked_pk);
1496 }
1497
1498 /*
1499 * list all public keys in the chained list
1500 */
1501 void list_public_keys(bool utc)
1502 {
1503 pubkey_list_t *p = pubkeys;
1504
1505 if (p != NULL)
1506 {
1507 whack_log(RC_COMMENT, " ");
1508 whack_log(RC_COMMENT, "List of Public Keys:");
1509 whack_log(RC_COMMENT, " ");
1510 }
1511
1512 while (p != NULL)
1513 {
1514 pubkey_t *key = p->key;
1515
1516 if (key->alg == PUBKEY_ALG_RSA)
1517 {
1518 char buf[BUF_LEN];
1519 char expires_buf[TIMETOA_BUF];
1520
1521 idtoa(&key->id, buf, BUF_LEN);
1522 strcpy(expires_buf, timetoa(&key->until_time, utc));
1523 whack_log(RC_COMMENT, "%s, %4d RSA Key %s, until %s %s",
1524
1525 timetoa(&key->installed_time, utc), 8*key->u.rsa.k, key->u.rsa.keyid,
1526 expires_buf,
1527 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1528 whack_log(RC_COMMENT," %s '%s'",
1529 enum_show(&ident_names, key->id.kind), buf);
1530 if (key->issuer.len > 0)
1531 {
1532 dntoa(buf, BUF_LEN, key->issuer);
1533 whack_log(RC_COMMENT," issuer: '%s'", buf);
1534 }
1535 if (key->serial.len > 0)
1536 {
1537 datatot(key->serial.ptr, key->serial.len, ':'
1538 , buf, BUF_LEN);
1539 whack_log(RC_COMMENT," serial: %s", buf);
1540 }
1541 }
1542 p = p->next;
1543 }
1544 }