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