7aea81fbff39a2352447d69a35cef85c7d331d20
[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 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 process_secret(secret_t *s, int whackfd)
776 {
777 err_t ugh = NULL;
778
779 s->kind = PPK_PSK; /* default */
780 if (*tok == '"' || *tok == '\'')
781 {
782 /* old PSK format: just a string */
783 ugh = process_psk_secret(&s->u.preshared_secret);
784 }
785 else if (tokeqword("psk"))
786 {
787 /* preshared key: quoted string or ttodata format */
788 ugh = !shift()? "unexpected end of record in PSK"
789 : process_psk_secret(&s->u.preshared_secret);
790 }
791 else if (tokeqword("rsa"))
792 {
793 /* RSA key: the fun begins.
794 * A braced list of keyword and value pairs.
795 */
796 s->kind = PPK_RSA;
797 if (!shift())
798 {
799 ugh = "bad RSA key syntax";
800 }
801 else if (tokeq("{"))
802 {
803 ugh = process_rsa_secret(&s->u.RSA_private_key);
804 }
805 else
806 {
807 ugh = process_rsa_keyfile(&s->u.RSA_private_key, whackfd);
808 }
809 }
810 else if (tokeqword("xauth"))
811 {
812 ugh = process_xauth(s);
813 }
814 else if (tokeqword("pin"))
815 {
816 ugh = process_pin(s, whackfd);
817 }
818 else
819 {
820 ugh = builddiag("unrecognized key format: %s", tok);
821 }
822
823 if (ugh != NULL)
824 {
825 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
826 , flp->filename, flp->lino, ugh);
827 pfree(s);
828 }
829 else if (flushline("expected record boundary in key"))
830 {
831 /* gauntlet has been run: install new secret */
832 lock_certs_and_keys("process_secret");
833 s->next = secrets;
834 secrets = s;
835 unlock_certs_and_keys("process_secrets");
836 }
837 }
838
839 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
840
841 static void
842 process_secret_records(int whackfd)
843 {
844 /* read records from ipsec.secrets and load them into our table */
845 for (;;)
846 {
847 (void)flushline(NULL); /* silently ditch leftovers, if any */
848 if (flp->bdry == B_file)
849 break;
850
851 flp->bdry = B_none; /* eat the Record Boundary */
852 (void)shift(); /* get real first token */
853
854 if (tokeqword("include"))
855 {
856 /* an include directive */
857 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
858 char *p = fn;
859 char *end_prefix = strrchr(flp->filename, '/');
860
861 if (!shift())
862 {
863 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
864 , flp->filename, flp->lino);
865 continue; /* abandon this record */
866 }
867
868 /* if path is relative and including file's pathname has
869 * a non-empty dirname, prefix this path with that dirname.
870 */
871 if (tok[0] != '/' && end_prefix != NULL)
872 {
873 size_t pl = end_prefix - flp->filename + 1;
874
875 /* "clamp" length to prevent problems now;
876 * will be rediscovered and reported later.
877 */
878 if (pl > sizeof(fn))
879 pl = sizeof(fn);
880 memcpy(fn, flp->filename, pl);
881 p += pl;
882 }
883 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
884 {
885 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
886 , flp->filename, flp->lino);
887 continue; /* abandon this record */
888 }
889 strcpy(p, tok);
890 (void) shift(); /* move to Record Boundary, we hope */
891 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
892 {
893 process_secrets_file(fn, whackfd);
894 tok = NULL; /* correct, but probably redundant */
895 }
896 }
897 else
898 {
899 /* expecting a list of indices and then the key info */
900 secret_t *s = alloc_thing(secret_t, "secret");
901
902 s->ids = NULL;
903 s->kind = PPK_PSK; /* default */
904 setchunk(s->u.preshared_secret, NULL, 0);
905 s->next = NULL;
906
907 for (;;)
908 {
909 if (tok[0] == '"' || tok[0] == '\'')
910 {
911 /* found key part */
912 process_secret(s, whackfd);
913 break;
914 }
915 else if (tokeq(":"))
916 {
917 /* found key part */
918 shift(); /* discard explicit separator */
919 process_secret(s, whackfd);
920 break;
921 }
922 else
923 {
924 /* an id
925 * See RFC2407 IPsec Domain of Interpretation 4.6.2
926 */
927 struct id id;
928 err_t ugh;
929
930 if (tokeq("%any"))
931 {
932 id = empty_id;
933 id.kind = ID_IPV4_ADDR;
934 ugh = anyaddr(AF_INET, &id.ip_addr);
935 }
936 else if (tokeq("%any6"))
937 {
938 id = empty_id;
939 id.kind = ID_IPV6_ADDR;
940 ugh = anyaddr(AF_INET6, &id.ip_addr);
941 }
942 else
943 {
944 ugh = atoid(tok, &id, FALSE);
945 }
946
947 if (ugh != NULL)
948 {
949 loglog(RC_LOG_SERIOUS
950 , "ERROR \"%s\" line %d: index \"%s\" %s"
951 , flp->filename, flp->lino, tok, ugh);
952 }
953 else
954 {
955 id_list_t *i = alloc_thing(id_list_t
956 , "id_list");
957
958 i->id = id;
959 unshare_id_content(&i->id);
960 i->next = s->ids;
961 s->ids = i;
962 /* DBG_log("id type %d: %s %.*s", i->kind, ip_str(&i->ip_addr), (int)i->name.len, i->name.ptr); */
963 }
964 if (!shift())
965 {
966 /* unexpected Record Boundary or EOF */
967 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of id list"
968 , flp->filename, flp->lino);
969 break;
970 }
971 }
972 }
973 }
974 }
975 }
976
977 static int
978 globugh(const char *epath, int eerrno)
979 {
980 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
981 return 1; /* stop glob */
982 }
983
984 static void
985 process_secrets_file(const char *file_pat, int whackfd)
986 {
987 struct file_lex_position pos;
988 char **fnp;
989 glob_t globbuf;
990
991 pos.depth = flp == NULL? 0 : flp->depth + 1;
992
993 if (pos.depth > 10)
994 {
995 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
996 return;
997 }
998
999 /* do globbing */
1000 {
1001 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1002
1003 if (r != 0)
1004 {
1005 switch (r)
1006 {
1007 case GLOB_NOSPACE:
1008 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1009 break;
1010 case GLOB_ABORTED:
1011 break; /* already logged */
1012 case GLOB_NOMATCH:
1013 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1014 break;
1015 default:
1016 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1017 break;
1018 }
1019 globfree(&globbuf);
1020 return;
1021 }
1022 }
1023
1024 /* for each file... */
1025 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1026 {
1027 if (lexopen(&pos, *fnp, FALSE))
1028 {
1029 plog("loading secrets from \"%s\"", *fnp);
1030 (void) flushline("file starts with indentation (continuation notation)");
1031 process_secret_records(whackfd);
1032 lexclose();
1033 }
1034 }
1035
1036 globfree(&globbuf);
1037 }
1038
1039 void
1040 free_preshared_secrets(void)
1041 {
1042 lock_certs_and_keys("free_preshared_secrets");
1043
1044 if (secrets != NULL)
1045 {
1046 secret_t *s, *ns;
1047
1048 plog("forgetting secrets");
1049
1050 for (s = secrets; s != NULL; s = ns)
1051 {
1052 id_list_t *i, *ni;
1053
1054 ns = s->next; /* grab before freeing s */
1055 for (i = s->ids; i != NULL; i = ni)
1056 {
1057 ni = i->next; /* grab before freeing i */
1058 free_id_content(&i->id);
1059 pfree(i);
1060 }
1061 switch (s->kind)
1062 {
1063 case PPK_PSK:
1064 pfree(s->u.preshared_secret.ptr);
1065 break;
1066 case PPK_RSA:
1067 free_RSA_private_content(&s->u.RSA_private_key);
1068 break;
1069 case PPK_XAUTH:
1070 pfree(s->u.xauth_secret.user_name.ptr);
1071 pfree(s->u.xauth_secret.user_password.ptr);
1072 break;
1073 case PPK_PIN:
1074 scx_release(s->u.smartcard);
1075 break;
1076 default:
1077 bad_case(s->kind);
1078 }
1079 pfree(s);
1080 }
1081 secrets = NULL;
1082 }
1083
1084 unlock_certs_and_keys("free_preshard_secrets");
1085 }
1086
1087 void
1088 load_preshared_secrets(int whackfd)
1089 {
1090 free_preshared_secrets();
1091 (void) process_secrets_file(shared_secrets_file, whackfd);
1092 }
1093
1094 /* public key machinery
1095 * Note: caller must set dns_auth_level.
1096 */
1097
1098 pubkey_t *
1099 public_key_from_rsa(const RSA_public_key_t *k)
1100 {
1101 pubkey_t *p = alloc_thing(pubkey_t, "pubkey");
1102
1103 p->id = empty_id; /* don't know, doesn't matter */
1104 p->issuer = empty_chunk;
1105 p->serial = empty_chunk;
1106 p->alg = PUBKEY_ALG_RSA;
1107
1108 memcpy(p->u.rsa.keyid, k->keyid, sizeof(p->u.rsa.keyid));
1109 p->u.rsa.k = k->k;
1110 mpz_init_set(&p->u.rsa.e, &k->e);
1111 mpz_init_set(&p->u.rsa.n, &k->n);
1112
1113 /* note that we return a 1 reference count upon creation:
1114 * invariant: recount > 0.
1115 */
1116 p->refcnt = 1;
1117 time(&p->installed_time);
1118 return p;
1119 }
1120
1121 /* Free a public key record.
1122 * As a convenience, this returns a pointer to next.
1123 */
1124 pubkey_list_t *
1125 free_public_keyentry(pubkey_list_t *p)
1126 {
1127 pubkey_list_t *nxt = p->next;
1128
1129 if (p->key != NULL)
1130 unreference_key(&p->key);
1131 pfree(p);
1132 return nxt;
1133 }
1134
1135 void
1136 free_public_keys(pubkey_list_t **keys)
1137 {
1138 while (*keys != NULL)
1139 *keys = free_public_keyentry(*keys);
1140 }
1141
1142 /* root of chained public key list */
1143
1144 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1145
1146 void
1147 free_remembered_public_keys(void)
1148 {
1149 free_public_keys(&pubkeys);
1150 }
1151
1152 /* transfer public keys from *keys list to front of pubkeys list */
1153 void
1154 transfer_to_public_keys(struct gw_info *gateways_from_dns
1155 #ifdef USE_KEYRR
1156 , pubkey_list_t **keys
1157 #endif /* USE_KEYRR */
1158 )
1159 {
1160 {
1161 struct gw_info *gwp;
1162
1163 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1164 {
1165 pubkey_list_t *pl = alloc_thing(pubkey_list_t, "from TXT");
1166
1167 pl->key = gwp->key; /* note: this is a transfer */
1168 gwp->key = NULL; /* really, it is! */
1169 pl->next = pubkeys;
1170 pubkeys = pl;
1171 }
1172 }
1173
1174 #ifdef USE_KEYRR
1175 {
1176 pubkey_list_t **pp = keys;
1177
1178 while (*pp != NULL)
1179 pp = &(*pp)->next;
1180 *pp = pubkeys;
1181 pubkeys = *keys;
1182 *keys = NULL;
1183 }
1184 #endif /* USE_KEYRR */
1185 }
1186
1187 /* decode of RSA pubkey chunk
1188 * - format specified in RFC 2537 RSA/MD5 Keys and SIGs in the DNS
1189 * - exponent length in bytes (1 or 3 octets)
1190 * + 1 byte if in [1, 255]
1191 * + otherwise 0x00 followed by 2 bytes of length
1192 * - exponent
1193 * - modulus
1194 */
1195 err_t
1196 unpack_RSA_public_key(RSA_public_key_t *rsa, const chunk_t *pubkey)
1197 {
1198 chunk_t exp;
1199 chunk_t mod;
1200
1201 if (pubkey->len < 3)
1202 return "RSA public key blob way to short"; /* not even room for length! */
1203
1204 if (pubkey->ptr[0] != 0x00)
1205 {
1206 setchunk(exp, pubkey->ptr + 1, pubkey->ptr[0]);
1207 }
1208 else
1209 {
1210 setchunk(exp, pubkey->ptr + 3
1211 , (pubkey->ptr[1] << BITS_PER_BYTE) + pubkey->ptr[2]);
1212 }
1213
1214 if (pubkey->len - (exp.ptr - pubkey->ptr) < exp.len + RSA_MIN_OCTETS_RFC)
1215 return "RSA public key blob too short";
1216
1217 mod.ptr = exp.ptr + exp.len;
1218 mod.len = &pubkey->ptr[pubkey->len] - mod.ptr;
1219
1220 if (mod.len < RSA_MIN_OCTETS)
1221 return RSA_MIN_OCTETS_UGH;
1222
1223 if (mod.len > RSA_MAX_OCTETS)
1224 return RSA_MAX_OCTETS_UGH;
1225
1226 init_RSA_public_key(rsa, exp, mod);
1227 rsa->k = mpz_sizeinbase(&rsa->n, 2); /* size in bits, for a start */
1228 rsa->k = (rsa->k + BITS_PER_BYTE - 1) / BITS_PER_BYTE; /* now octets */
1229 DBG(DBG_RAW,
1230 RSA_show_public_key(rsa)
1231 )
1232
1233 if (rsa->k != mod.len)
1234 {
1235 mpz_clear(&rsa->e);
1236 mpz_clear(&rsa->n);
1237 return "RSA modulus shorter than specified";
1238 }
1239
1240 return NULL;
1241 }
1242
1243 static void
1244 install_public_key(pubkey_t *pk, pubkey_list_t **head)
1245 {
1246 pubkey_list_t *p = alloc_thing(pubkey_list_t, "pubkey entry");
1247
1248 unshare_id_content(&pk->id);
1249
1250 /* copy issuer dn */
1251 if (pk->issuer.ptr != NULL)
1252 pk->issuer.ptr = clone_bytes(pk->issuer.ptr, pk->issuer.len, "issuer dn");
1253
1254 /* copy serial number */
1255 if (pk->serial.ptr != NULL)
1256 pk->serial.ptr = clone_bytes(pk->serial.ptr, pk->serial.len, "serialNumber");
1257
1258 /* store the time the public key was installed */
1259 time(&pk->installed_time);
1260
1261 /* install new key at front */
1262 p->key = reference_key(pk);
1263 p->next = *head;
1264 *head = p;
1265 }
1266
1267
1268 void
1269 delete_public_keys(const struct id *id, enum pubkey_alg alg
1270 , chunk_t issuer, chunk_t serial)
1271 {
1272 pubkey_list_t **pp, *p;
1273 pubkey_t *pk;
1274
1275 for (pp = &pubkeys; (p = *pp) != NULL; )
1276 {
1277 pk = p->key;
1278
1279 if (same_id(id, &pk->id) && pk->alg == alg
1280 && (issuer.ptr == NULL || pk->issuer.ptr == NULL
1281 || same_dn(issuer, pk->issuer))
1282 && same_serial(serial, pk->serial))
1283 *pp = free_public_keyentry(p);
1284 else
1285 pp = &p->next;
1286 }
1287 }
1288
1289 pubkey_t *
1290 reference_key(pubkey_t *pk)
1291 {
1292 pk->refcnt++;
1293 return pk;
1294 }
1295
1296 void
1297 unreference_key(pubkey_t **pkp)
1298 {
1299 pubkey_t *pk = *pkp;
1300 char b[BUF_LEN];
1301
1302 if (pk == NULL)
1303 return;
1304
1305 /* print stuff */
1306 DBG(DBG_CONTROLMORE,
1307 idtoa(&pk->id, b, sizeof(b));
1308 DBG_log("unreference key: %p %s cnt %d--", pk, b, pk->refcnt)
1309 )
1310
1311 /* cancel out the pointer */
1312 *pkp = NULL;
1313
1314 passert(pk->refcnt != 0);
1315 pk->refcnt--;
1316 if (pk->refcnt == 0)
1317 free_public_key(pk);
1318 }
1319
1320 err_t
1321 add_public_key(const struct id *id
1322 , enum dns_auth_level dns_auth_level
1323 , enum pubkey_alg alg
1324 , const chunk_t *key
1325 , pubkey_list_t **head)
1326 {
1327 pubkey_t *pk = alloc_thing(pubkey_t, "pubkey");
1328
1329 /* first: algorithm-specific decoding of key chunk */
1330 switch (alg)
1331 {
1332 case PUBKEY_ALG_RSA:
1333 {
1334 err_t ugh = unpack_RSA_public_key(&pk->u.rsa, key);
1335
1336 if (ugh != NULL)
1337 {
1338 pfree(pk);
1339 return ugh;
1340 }
1341 }
1342 break;
1343 default:
1344 bad_case(alg);
1345 }
1346
1347 pk->id = *id;
1348 pk->dns_auth_level = dns_auth_level;
1349 pk->alg = alg;
1350 pk->until_time = UNDEFINED_TIME;
1351 pk->issuer = empty_chunk;
1352 pk->serial = empty_chunk;
1353
1354 install_public_key(pk, head);
1355 return NULL;
1356 }
1357
1358 /* extract id and public key from x.509 certificate and
1359 * insert it into a pubkeyrec
1360 */
1361 void
1362 add_x509_public_key(x509cert_t *cert , time_t until
1363 , enum dns_auth_level dns_auth_level)
1364 {
1365 generalName_t *gn;
1366 pubkey_t *pk;
1367 cert_t c = { CERT_X509_SIGNATURE, {cert} };
1368
1369 /* we support RSA only */
1370 if (cert->subjectPublicKeyAlgorithm != PUBKEY_ALG_RSA)
1371 return;
1372
1373 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1374 pk = allocate_RSA_public_key(c);
1375 pk->id.kind = ID_DER_ASN1_DN;
1376 pk->id.name = cert->subject;
1377 pk->dns_auth_level = dns_auth_level;
1378 pk->until_time = until;
1379 pk->issuer = cert->issuer;
1380 pk->serial = cert->serialNumber;
1381 delete_public_keys(&pk->id, pk->alg, pk->issuer, pk->serial);
1382 install_public_key(pk, &pubkeys);
1383
1384 gn = cert->subjectAltName;
1385
1386 while (gn != NULL) /* insert all subjectAltNames */
1387 {
1388 struct id id = empty_id;
1389
1390 gntoid(&id, gn);
1391 if (id.kind != ID_NONE)
1392 {
1393 pk = allocate_RSA_public_key(c);
1394 pk->id = id;
1395 pk->dns_auth_level = dns_auth_level;
1396 pk->until_time = until;
1397 pk->issuer = cert->issuer;
1398 pk->serial = cert->serialNumber;
1399 delete_public_keys(&pk->id, pk->alg, pk->issuer, pk->serial);
1400 install_public_key(pk, &pubkeys);
1401 }
1402 gn = gn->next;
1403 }
1404 }
1405
1406 /* extract id and public key from OpenPGP certificate and
1407 * insert it into a pubkeyrec
1408 */
1409 void
1410 add_pgp_public_key(pgpcert_t *cert , time_t until
1411 , enum dns_auth_level dns_auth_level)
1412 {
1413 pubkey_t *pk;
1414 cert_t c;
1415
1416 c.type = CERT_PGP;
1417 c.u.pgp = cert;
1418
1419 /* we support RSA only */
1420 if (cert->pubkeyAlg != PUBKEY_ALG_RSA)
1421 {
1422 plog(" RSA public keys supported only");
1423 return;
1424 }
1425
1426 pk = allocate_RSA_public_key(c);
1427 pk->id.kind = ID_KEY_ID;
1428 pk->id.name.ptr = cert->fingerprint;
1429 pk->id.name.len = PGP_FINGERPRINT_SIZE;
1430 pk->dns_auth_level = dns_auth_level;
1431 pk->until_time = until;
1432 delete_public_keys(&pk->id, pk->alg, empty_chunk, empty_chunk);
1433 install_public_key(pk, &pubkeys);
1434 }
1435
1436 /* when a X.509 certificate gets revoked, all instances of
1437 * the corresponding public key must be removed
1438 */
1439 void
1440 remove_x509_public_key(const x509cert_t *cert)
1441 {
1442 const cert_t c = {CERT_X509_SIGNATURE, {cert}};
1443 pubkey_list_t *p, **pp;
1444 pubkey_t *revoked_pk;
1445
1446 revoked_pk = allocate_RSA_public_key(c);
1447 p = pubkeys;
1448 pp = &pubkeys;
1449
1450 while(p != NULL)
1451 {
1452 if (same_RSA_public_key(&p->key->u.rsa, &revoked_pk->u.rsa))
1453 {
1454 /* remove p from list and free memory */
1455 *pp = free_public_keyentry(p);
1456 loglog(RC_LOG_SERIOUS,
1457 "invalid RSA public key deleted");
1458 }
1459 else
1460 {
1461 pp = &p->next;
1462 }
1463 p =*pp;
1464 }
1465 free_public_key(revoked_pk);
1466 }
1467
1468 /*
1469 * list all public keys in the chained list
1470 */
1471 void list_public_keys(bool utc)
1472 {
1473 pubkey_list_t *p = pubkeys;
1474
1475 if (p != NULL)
1476 {
1477 whack_log(RC_COMMENT, " ");
1478 whack_log(RC_COMMENT, "List of Public Keys:");
1479 whack_log(RC_COMMENT, " ");
1480 }
1481
1482 while (p != NULL)
1483 {
1484 pubkey_t *key = p->key;
1485
1486 if (key->alg == PUBKEY_ALG_RSA)
1487 {
1488 char buf[BUF_LEN];
1489 char expires_buf[TIMETOA_BUF];
1490
1491 idtoa(&key->id, buf, BUF_LEN);
1492 strcpy(expires_buf, timetoa(&key->until_time, utc));
1493 whack_log(RC_COMMENT, "%s, %4d RSA Key %s, until %s %s",
1494
1495 timetoa(&key->installed_time, utc), 8*key->u.rsa.k, key->u.rsa.keyid,
1496 expires_buf,
1497 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1498 whack_log(RC_COMMENT," %s '%s'",
1499 enum_show(&ident_names, key->id.kind), buf);
1500 if (key->issuer.len > 0)
1501 {
1502 dntoa(buf, BUF_LEN, key->issuer);
1503 whack_log(RC_COMMENT," issuer: '%s'", buf);
1504 }
1505 if (key->serial.len > 0)
1506 {
1507 datatot(key->serial.ptr, key->serial.len, ':'
1508 , buf, BUF_LEN);
1509 whack_log(RC_COMMENT," serial: %s", buf);
1510 }
1511 }
1512 p = p->next;
1513 }
1514 }