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