1 /* mechanisms for preshared keys (public, private, and preshared secrets)
2 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
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>.
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
14 * RCSID $Id: preshared.c,v 1.60 2002/03/22 23:38:28 dhr Exp $
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
29 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
34 # define GLOB_ABORTED GLOB_ABEND /* fix for old versions */
39 #include "constants.h"
43 #include "connections.h" /* needs id.h */
45 #include "preshared.h"
46 #include "adns.h" /* needs <resolv.h> */
47 #include "dnskey.h" /* needs preshared.h and adns.h */
49 #include "whack.h" /* for RC_LOG_SERIOUS */
52 /* Maximum length of filename and passphrase buffer */
57 #define PB_STREAM_UNDEFINED
58 #include "nat_traversal.h"
66 static const struct fld RSA_private_field[] =
68 { "Modulus", offsetof(struct RSA_private_key, pub.n) },
69 { "PublicExponent", offsetof(struct RSA_private_key, pub.e) },
71 { "PrivateExponent", offsetof(struct RSA_private_key, d) },
72 { "Prime1", offsetof(struct RSA_private_key, p) },
73 { "Prime2", offsetof(struct RSA_private_key, q) },
74 { "Exponent1", offsetof(struct RSA_private_key, dP) },
75 { "Exponent2", offsetof(struct RSA_private_key, dQ) },
76 { "Coefficient", offsetof(struct RSA_private_key, qInv) },
81 RSA_show_key_fields(struct RSA_private_key *k, int fieldcnt)
85 DBG_log(" keyid: *%s", k->pub.keyid);
87 for (p = RSA_private_field; p < &RSA_private_field[fieldcnt]; p++)
89 MP_INT *n = (MP_INT *) ((char *)k + p->offset);
90 size_t sz = mpz_sizeinbase(n, 16);
91 char buf[2048/4 + 2]; /* ought to be big enough */
93 passert(sz <= sizeof(buf));
94 mpz_get_str(buf, 16, n);
96 DBG_log(" %s: %s", p->name, buf);
100 /* debugging info that compromises security! */
102 RSA_show_private_key(struct RSA_private_key *k)
104 RSA_show_key_fields(k, elemsof(RSA_private_field));
108 RSA_show_public_key(struct RSA_public_key *k)
110 /* Kludge: pretend that it is a private key, but only display the
111 * first two fields (which are the public key).
113 passert(offsetof(struct RSA_private_key, pub) == 0);
114 RSA_show_key_fields((struct RSA_private_key *)k, 2);
119 RSA_private_key_sanity(struct RSA_private_key *k)
121 /* note that the *last* error found is reported */
125 #ifdef DEBUG /* debugging info that compromises security */
126 DBG(DBG_PRIVATE, RSA_show_private_key(k));
129 /* PKCS#1 1.5 section 6 requires modulus to have at least 12 octets.
130 * We actually require more (for security).
132 if (k->pub.k < RSA_MIN_OCTETS)
133 return RSA_MIN_OCTETS_UGH;
135 /* we picked a max modulus size to simplify buffer allocation */
136 if (k->pub.k > RSA_MAX_OCTETS)
137 return RSA_MAX_OCTETS_UGH;
143 /* check that n == p * q */
144 mpz_mul(u, &k->p, &k->q);
145 if (mpz_cmp(u, &k->pub.n) != 0)
148 /* check that e divides neither p-1 nor q-1 */
149 mpz_sub_ui(t, &k->p, 1);
150 mpz_mod(t, t, &k->pub.e);
151 if (mpz_cmp_ui(t, 0) == 0)
152 ugh = "e divides p-1";
154 mpz_sub_ui(t, &k->q, 1);
155 mpz_mod(t, t, &k->pub.e);
156 if (mpz_cmp_ui(t, 0) == 0)
157 ugh = "e divides q-1";
159 /* check that d is e^-1 (mod lcm(p-1, q-1)) */
160 /* see PKCS#1v2, aka RFC 2437, for the "lcm" */
161 mpz_sub_ui(q1, &k->q, 1);
162 mpz_sub_ui(u, &k->p, 1);
163 mpz_gcd(t, u, q1); /* t := gcd(p-1, q-1) */
164 mpz_mul(u, u, q1); /* u := (p-1) * (q-1) */
165 mpz_divexact(u, u, t); /* u := lcm(p-1, q-1) */
167 mpz_mul(t, &k->d, &k->pub.e);
169 if (mpz_cmp_ui(t, 1) != 0)
170 ugh = "(d * e) mod (lcm(p-1, q-1)) != 1";
172 /* check that dP is d mod (p-1) */
173 mpz_sub_ui(u, &k->p, 1);
174 mpz_mod(t, &k->d, u);
175 if (mpz_cmp(t, &k->dP) != 0)
176 ugh = "dP is not congruent to d mod (p-1)";
178 /* check that dQ is d mod (q-1) */
179 mpz_sub_ui(u, &k->q, 1);
180 mpz_mod(t, &k->d, u);
181 if (mpz_cmp(t, &k->dQ) != 0)
182 ugh = "dQ is not congruent to d mod (q-1)";
184 /* check that qInv is (q^-1) mod p */
185 mpz_mul(t, &k->qInv, &k->q);
186 mpz_mod(t, t, &k->p);
187 if (mpz_cmp_ui(t, 1) != 0)
188 ugh = "qInv is not conguent ot (q^-1) mod p";
196 const char *shared_secrets_file = SHARED_SECRETS_FILE;
200 struct id_list *next;
205 enum PrivateKeyKind kind;
207 chunk_t preshared_secret;
208 struct RSA_private_key RSA_private_key;
213 static struct pubkeyrec*
214 allocate_RSA_public_key(const x509cert_t *cert)
216 struct pubkeyrec *p = alloc_thing(struct pubkeyrec, "pubkeyrec");
217 chunk_t e = cert->publicExponent;
218 chunk_t n = cert->modulus;
220 /* eliminate leading zero byte in modulus from ASN.1 coding */
225 n_to_mpz(&p->u.rsa.e, e.ptr, e.len);
226 n_to_mpz(&p->u.rsa.n, n.ptr, n.len);
229 p->u.rsa.keyid[0] = '\0'; /* in case of splitkeytoid failure */
230 splitkeytoid(e.ptr, e.len, n.ptr, n.len, p->u.rsa.keyid, sizeof(p->u.rsa.keyid));
233 DBG(DBG_PRIVATE, RSA_show_public_key(&p->u.rsa));
236 p->u.rsa.k = mpz_sizeinbase(&p->u.rsa.n, 2); /* size in bits, for a start */
237 p->u.rsa.k = (p->u.rsa.k + BITS_PER_BYTE - 1) / BITS_PER_BYTE; /* now octets */
239 p->alg = PUBKEY_ALG_RSA;
245 struct secret *secrets = NULL;
247 /* find the struct secret associated with the combination of
248 * me and the peer. We match the Id (if none, the IP address).
249 * Failure is indicated by a NULL.
251 static const struct secret *
252 get_id_secret(enum PrivateKeyKind kind
256 , struct pubkeyrec *my_public_key)
259 match_default = 0x01,
265 unsigned int best_match = 0;
266 struct secret *best = NULL;
269 for (s = secrets; s != NULL; s = s->next)
273 unsigned int match = 0;
277 /* a default (signified by lack of ids):
278 * accept if no more specific match found
280 match = match_default;
284 /* check if both ends match ids */
287 for (i = s->ids; i != NULL; i = i->next)
289 if (same_id(my_id, &i->id))
292 if (same_id(his_id, &i->id))
296 /* If our end matched the only id in the list,
297 * default to matching any peer.
298 * A more specific match will trump this.
300 if (match == match_me
301 && s->ids->next == NULL)
302 match |= match_default;
305 if (my_public_key != NULL &&
306 same_RSA_public_key(&s->u.RSA_private_key.pub, &my_public_key->u.rsa))
308 match = match_pubkey;
311 if (match == match_pubkey)
314 break; /* we have found the private key - no sense in searching further */
320 /* if this is an asymmetric (eg. public key) system,
321 * allow this-side-only match to count, even if
322 * there are other ids in the list.
327 case match_default: /* default all */
328 case match_me | match_default: /* default peer */
329 case match_me | match_him: /* explicit */
330 if (match == best_match)
332 /* two good matches are equally good:
340 same = s->u.preshared_secret.len == best->u.preshared_secret.len
341 && memcmp(s->u.preshared_secret.ptr, best->u.preshared_secret.ptr, s->u.preshared_secret.len) == 0;
344 /* Dirty trick: since we have code to compare
345 * RSA public keys, but not private keys, we
346 * make the assumption that equal public keys
347 * mean equal private keys. This ought to work.
349 same = same_RSA_public_key(&s->u.RSA_private_key.pub
350 , &best->u.RSA_private_key.pub);
357 loglog(RC_LOG_SERIOUS, "multiple ipsec.secrets entries with distinct secrets match endpoints:"
358 " first secret used");
359 best = s; /* list is backwards: take latest in list */
362 else if (match > best_match)
364 /* this is the best match so far */
374 static const struct secret *
375 get_secret(struct connection *c, enum PrivateKeyKind kind, bool asym)
377 const struct secret *best = NULL;
378 struct id *my_id = &c->this.id
380 , *his_id = &c->that.id;
382 struct pubkeyrec *my_public_key = NULL;
384 /* is there a certificate assigned to this connection? */
385 if (kind == PPK_RSA && c->this.cert != NULL)
387 my_public_key = allocate_RSA_public_key(c->this.cert);
390 if (his_id_was_instantiated(c))
392 /* roadwarrior: replace him with ID_NONE */
393 rw_id.kind = ID_NONE;
397 else if ((nat_traversal_enabled) && (c->policy & POLICY_PSK) &&
398 (kind == PPK_PSK) && (
399 ((c->kind == CK_TEMPLATE) && (c->that.id.kind == ID_NONE)) ||
400 ((c->kind == CK_INSTANCE) && (id_is_ipaddr(&c->that.id)))))
402 /* roadwarrior: replace him with ID_NONE */
403 rw_id.kind = ID_NONE;
408 best = get_id_secret(kind, asym, my_id, his_id, my_public_key);
410 /* replace me with ID_NONE and try again */
411 my_rw_id.kind = ID_NONE;
413 best = get_id_secret(kind, asym, my_id, his_id, my_public_key);
416 if (my_public_key != NULL)
418 free_public_key(my_public_key);
423 /* find the appropriate preshared key (see get_secret).
424 * Failure is indicated by a NULL pointer.
425 * Note: the result is not to be freed by the caller.
428 get_preshared_secret(struct connection *c)
430 const struct secret *s = get_secret(c, PPK_PSK, FALSE);
435 DBG_log("no Preshared Key Found");
437 DBG_dump_chunk("Preshared Key", s->u.preshared_secret);
440 return s == NULL? NULL : &s->u.preshared_secret;
443 /* find the appropriate RSA private key (see get_secret).
444 * Failure is indicated by a NULL pointer.
446 const struct RSA_private_key *
447 get_RSA_private_key(struct connection *c)
449 const struct secret *s = get_secret(c, PPK_RSA, TRUE);
451 return s == NULL? NULL : &s->u.RSA_private_key;
454 /* digest a secrets file
456 * The file is a sequence of records. A record is a maximal sequence of
457 * tokens such that the first, and only the first, is in the first column
460 * Tokens are generally separated by whitespace and are key words, ids,
461 * strings, or data suitable for ttodata(3). As a nod to convention,
462 * a trailing ":" on what would otherwise be a token is taken as a
463 * separate token. If preceded by whitespace, a "#" is taken as starting
464 * a comment: it and the rest of the line are ignored.
466 * One kind of record is an include directive. It starts with "include".
467 * The filename is the only other token in the record.
468 * If the filename does not start with /, it is taken to
469 * be relative to the directory containing the current file.
471 * The other kind of record describes a key. It starts with a
472 * sequence of ids and ends with key information. Each id
473 * is an IP address, a Fully Qualified Domain Name (which will immediately
474 * be resolved), or @FQDN which will be left as a name.
476 * The key part can be in several forms.
478 * The old form of the key is still supported: a simple
479 * quoted strings (with no escapes) is taken as a preshred key.
481 * The new form starts the key part with a ":".
483 * For Preshared Key, use the "PSK" keyword, and follow it by a string
484 * or a data token suitable for ttodata(3).
486 * For RSA Private Key, use the "RSA" keyword, followed by a
487 * brace-enclosed list of key field keywords and data values.
488 * The data values are large integers to be decoded by ttodata(3).
489 * The fields are a subset of those used by BIND 8.2 and have the
493 struct secrets_file_position
495 int depth; /* how deeply we are nested */
498 enum { B_none, B_record, B_file } bdry; /* current boundary */
499 int lino; /* line number in file */
500 char buffer[2049]; /* note: one extra char for our use (jamming '"') */
501 char *cur; /* cursor */
502 char under; /* except in shift(): character orignally at *cur */
503 struct secrets_file_position *previous;
506 static struct secrets_file_position *sfp = NULL;
508 /* Token decoding: shift() loads the next token into tok.
509 * Iff a token starts at the left margin, it is considered
510 * to be the first in a record. We create a special condition,
511 * Record Boundary (analogous to EOF), just before such a token.
512 * We are unwilling to shift through a record boundary:
513 * it must be overridden first.
514 * Returns FALSE iff Record Boundary or EOF (i.e. no token);
515 * tok will then be NULL.
518 static void process_secrets_file(const char *file_pat);
521 #define tokeq(s) (streq(tok, (s)))
522 #define tokeqword(s) (strcasecmp(tok, (s)) == 0)
528 char *sor = NULL; /* start of record for any new lines */
530 passert(sfp->bdry == B_none);
539 case '\0': /* end of line */
540 case '#': /* comment to end of line: treat as end of line */
541 /* get the next line */
542 if (fgets(sfp->buffer, sizeof(sfp->buffer)-1, sfp->fp) == NULL)
545 tok = sfp->cur = NULL;
550 /* strip trailing whitespace, including \n */
552 for (p = sfp->buffer+strlen(sfp->buffer)-1; p>sfp->buffer; p--)
558 sor = p = sfp->buffer;
560 break; /* try again for a token */
562 case ' ': /* whitespace */
565 break; /* try again for a token */
567 case '"': /* quoted token */
571 /* we have a quoted token: note and advance to its end */
576 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unterminated string"
577 , sfp->filename, sfp->lino);
578 p = tok + strlen(tok);
582 p++; /* include delimiter in token */
585 /* remember token delimiter and replace with '\0' */
595 /* we seem to have a token: note and advance to its end */
598 if (p[0] == '0' && p[1] == 't')
600 /* 0t... token goes to end of line */
605 /* "ordinary" token: up to whitespace or end of line */
608 } while (*p != '\0' && !isspace(*p))
611 /* fudge to separate ':' from a preceding adjacent token */
612 if (p-1 > tok && p[-1] == ':')
616 /* remember token delimiter and replace with '\0' */
623 /* we have a start-of-record: return it, deferring "real" token */
624 sfp->bdry = B_record;
633 /* ensures we are at a Record (or File) boundary, optionally warning if not */
636 flushline(const char *m)
638 if (sfp->bdry != B_none)
645 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s", sfp->filename, sfp->lino, m);
646 do ; while (shift());
651 /* parse PSK from file */
653 process_psk_secret(chunk_t *psk)
657 if (*tok == '"' || *tok == '\'')
659 clonetochunk(*psk, tok+1, sfp->cur - tok - 2, "PSK");
664 char buf[2048]; /* limit on size of binary representation of key */
667 ugh = ttodatav(tok, sfp->cur - tok, 0, buf, sizeof(buf), &sz
668 , diag_space, sizeof(diag_space));
671 /* ttodata didn't like PSK data */
672 ugh = builddiag("PSK data malformed (%s): %s", ugh, tok);
676 clonetochunk(*psk, buf, sz, "PSK");
683 /* Parse fields of RSA private key.
684 * A braced list of keyword and value pairs.
685 * At the moment, each field is required, in order.
686 * The fields come from BIND 8.2's representation
689 process_rsa_secret(struct RSA_private_key *rsak)
691 char buf[2048]; /* limit on size of binary representation of key */
694 /* save bytes of Modulus and PublicExponent for keyid calculation */
695 unsigned char ebytes[sizeof(buf)];
696 unsigned char *eb_next = ebytes;
697 chunk_t pub_bytes[2];
698 chunk_t *pb_next = &pub_bytes[0];
700 for (p = RSA_private_field; p < &RSA_private_field[elemsof(RSA_private_field)]; p++)
707 return "premature end of RSA key";
709 else if (!tokeqword(p->name))
711 return builddiag("%s keyword not found where expected in RSA key"
715 && (!tokeq(":") || shift()))) /* ignore optional ":" */
717 return "premature end of RSA key";
719 else if (NULL != (ugh = ttodatav(tok, sfp->cur - tok
720 , 0, buf, sizeof(buf), &sz, diag_space, sizeof(diag_space))))
722 /* in RSA key, ttodata didn't like */
723 return builddiag("RSA data malformed (%s): %s", ugh, tok);
727 MP_INT *n = (MP_INT *) ((char *)rsak + p->offset);
729 n_to_mpz(n, buf, sz);
730 if (pb_next < &pub_bytes[elemsof(pub_bytes)])
732 if (eb_next - ebytes + sz > sizeof(ebytes))
733 return "public key takes too many bytes";
735 setchunk(*pb_next, eb_next, sz);
736 memcpy(eb_next, buf, sz);
740 #if 0 /* debugging info that compromises security */
742 size_t sz = mpz_sizeinbase(n, 16);
743 char buf[2048/4 + 2]; /* ought to be big enough */
745 passert(sz <= sizeof(buf));
746 mpz_get_str(buf, 16, n);
748 loglog(RC_LOG_SERIOUS, "%s: %s", p->name, buf);
754 /* We require an (indented) '}' and the end of the record.
755 * We break down the test so that the diagnostic will be
756 * more helpful. Some people don't seem to wish to indent
759 if (!shift() || !tokeq("}"))
761 return "malformed end of RSA private key -- indented '}' required";
765 return "malformed end of RSA private key -- unexpected token after '}'";
769 unsigned bits = mpz_sizeinbase(&rsak->pub.n, 2);
771 rsak->pub.k = (bits + BITS_PER_BYTE - 1) / BITS_PER_BYTE;
772 rsak->pub.keyid[0] = '\0'; /* in case of splitkeytoid failure */
773 splitkeytoid(pub_bytes[1].ptr, pub_bytes[1].len
774 , pub_bytes[0].ptr, pub_bytes[0].len
775 , rsak->pub.keyid, sizeof(rsak->pub.keyid));
776 return RSA_private_key_sanity(rsak);
781 process_secret(struct secret *s)
785 s->kind = PPK_PSK; /* default */
786 if (*tok == '"' || *tok == '\'')
788 /* old PSK format: just a string */
789 ugh = process_psk_secret(&s->u.preshared_secret);
791 else if (tokeqword("psk"))
793 /* preshared key: quoted string or ttodata format */
794 ugh = !shift()? "unexpected end of record in PSK"
795 : process_psk_secret(&s->u.preshared_secret);
797 else if (tokeqword("rsa"))
799 /* RSA key: the fun begins.
800 * A braced list of keyword and value pairs.
805 ugh = "bad RSA key syntax";
809 ugh = process_rsa_secret(&s->u.RSA_private_key);
813 /* we expect the filename of a PKCS#1 private key file */
814 char filename[BUF_LEN];
815 char passphrase[BUF_LEN];
816 pkcs1privkey_t *key = NULL;
818 memset(filename, '\0', BUF_LEN);
819 memset(passphrase, '\0', BUF_LEN);
821 if (*tok == '"' || *tok == '\'') /* quoted filename */
822 memcpy(filename, tok+1, sfp->cur - tok - 2);
824 memcpy(filename, tok, sfp->cur - tok);
828 /* we expect an appended passphrase */
829 if (*tok == '"' || *tok == '\'') /* quoted passphrase */
830 memcpy(passphrase, tok+1, sfp->cur - tok - 2);
832 memcpy(passphrase, tok, sfp->cur - tok);
836 ugh = "RSA private key file -- unexpected token after passphrase";
840 key = load_pkcs1_private_key(filename, passphrase);
843 ugh = "error loading RSA private key file";
848 for (i = 0; ugh == NULL && i < elemsof(RSA_private_field); i++)
850 MP_INT *n = (MP_INT *) ((char *)&s->u.RSA_private_key +
851 RSA_private_field[i].offset);
852 n_to_mpz(n, key->field[i].ptr, key->field[i].len);
855 unsigned bits = mpz_sizeinbase(&s->u.RSA_private_key.pub.n, 2);
856 chunk_t n = key->field[0]; /* public modulus n */
857 chunk_t e = key->field[1]; /* public exponent e */
859 /* eliminate leading zero byte in modulus from ASN.1 coding */
865 s->u.RSA_private_key.pub.k = (bits + BITS_PER_BYTE - 1) / BITS_PER_BYTE;
868 s->u.RSA_private_key.pub.keyid[0] = '\0'; /* in case of splitkeytoid failure */
869 splitkeytoid(e.ptr, e.len, n.ptr, n.len
870 , s->u.RSA_private_key.pub.keyid, sizeof(s->u.RSA_private_key.pub.keyid));
872 ugh = RSA_private_key_sanity(&s->u.RSA_private_key);
874 pfree(key->pkcs1object.ptr);
881 ugh = builddiag("unrecognized key format: %s", tok);
886 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
887 , sfp->filename, sfp->lino, ugh);
889 else if (flushline("expected record boundary in key"))
891 /* gauntlet has been run: install new secret */
898 process_secret_records(void)
903 char **h_addr_list_element;
904 int h_addr_list_size = 0;
905 size_t strlength = 0;
907 int multiple_ips = FALSE;
908 /* read records from ipsec.secrets and load them into our table */
911 (void)flushline(NULL); /* silently ditch leftovers, if any */
912 if (sfp->bdry == B_file)
915 sfp->bdry = B_none; /* eat the Record Boundary */
916 (void)shift(); /* get real first token */
918 if (tokeqword("include"))
920 /* an include directive */
921 char fn[2048]; /* space for filename (I hope) */
923 char *end_prefix = strrchr(sfp->filename, '/');
927 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
928 , sfp->filename, sfp->lino);
929 continue; /* abandon this record */
932 /* if path is relative and including file's pathname has
933 * a non-empty dirname, prefix this path with that dirname.
935 if (tok[0] != '/' && end_prefix != NULL)
937 size_t pl = end_prefix - sfp->filename + 1;
939 /* "clamp" length to prevent problems now;
940 * will be rediscovered and reported later.
944 memcpy(fn, sfp->filename, pl);
947 if (sfp->cur - tok >= &fn[sizeof(fn)] - p)
949 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
950 , sfp->filename, sfp->lino);
951 continue; /* abandon this record */
954 (void) shift(); /* move to Record Boundary, we hope */
955 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
957 process_secrets_file(fn);
958 tok = NULL; /* correct, but probably redundant */
963 /* expecting a list of indices and then the key info */
964 struct secret *s = alloc_thing(struct secret, "secret");
967 s->kind = PPK_PSK; /* default */
968 setchunk(s->u.preshared_secret, NULL, 0);
973 if (tok[0] == '"' || tok[0] == '\'')
982 shift(); /* discard explicit separator */
989 * See RFC2407 IPsec Domain of Interpretation 4.6.2
997 id.kind = ID_IPV4_ADDR;
998 ugh = anyaddr(AF_INET, &id.ip_addr);
1000 else if (tokeq("%any6"))
1003 id.kind = ID_IPV6_ADDR;
1004 ugh = anyaddr(AF_INET6, &id.ip_addr);
1008 ugh = atoid(tok, &id);
1012 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s \"%s\""
1013 , sfp->filename, sfp->lino, ugh, tok);
1017 struct id_list *i = alloc_thing(struct id_list
1021 unshare_id_content(&i->id);
1024 /* DBG_log("id type %d: %s %.*s", i->kind, ip_str(&i->ip_addr), (int)i->name.len, i->name.ptr); */
1028 /* unexpected Record Boundary or EOF */
1029 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of id list"
1030 , sfp->filename, sfp->lino);
1040 globugh(const char *epath, int eerrno)
1042 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
1043 return 1; /* stop glob */
1047 process_secrets_file(const char *file_pat)
1049 struct secrets_file_position pos;
1053 pos.depth = sfp == NULL? 0 : sfp->depth + 1;
1057 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
1063 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1070 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1073 break; /* already logged */
1075 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1078 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1089 /* for each file... */
1090 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1092 #if defined(CONFIG_SNAPGEAR) || defined(CONFIG_SECUREEDGE)
1096 len = strlen(*fnp) + sizeof("ipsec showfile %s");
1097 cmd = (char *) malloc(len);
1099 log_errno((e, "fail to allocate memory"));
1100 continue; /* try the next one */
1102 snprintf(cmd, len, "ipsec showfile %s", *fnp);
1103 pos.filename = *fnp;
1104 pos.fp = popen(cmd, "r");
1107 log_errno((e, "could not open \"%s\"", cmd));
1109 continue; /* try the next one */
1113 pos.filename = *fnp;
1114 pos.fp = fopen(pos.filename, "r");
1117 log_errno((e, "could not open \"%s\"", pos.filename));
1118 continue; /* try the next one */
1122 log("loading secrets from \"%s\"", pos.filename);
1127 pos.cur = pos.buffer; /* nothing loaded yet */
1128 pos.under = *pos.cur = '\0';
1130 (void) shift(); /* prime tok */
1131 (void) flushline("file starts with indentation (continuation notation)");
1132 process_secret_records();
1133 #if defined(CONFIG_SNAPGEAR) || defined(CONFIG_SECUREEDGE)
1140 sfp = pos.previous; /* restore old state */
1144 free_preshared_secrets(void)
1146 if (secrets != NULL)
1148 struct secret *s, *ns;
1150 log("forgetting secrets");
1152 for (s = secrets; s != NULL; s = ns)
1154 struct id_list *i, *ni;
1156 ns = s->next; /* grab before freeing s */
1157 for (i = s->ids; i != NULL; i = ni)
1159 ni = i->next; /* grab before freeing i */
1160 free_id_content(&i->id);
1166 pfree(s->u.preshared_secret.ptr);
1169 free_RSA_public_content(&s->u.RSA_private_key.pub);
1170 mpz_clear(&s->u.RSA_private_key.d);
1171 mpz_clear(&s->u.RSA_private_key.p);
1172 mpz_clear(&s->u.RSA_private_key.q);
1173 mpz_clear(&s->u.RSA_private_key.dP);
1174 mpz_clear(&s->u.RSA_private_key.dQ);
1175 mpz_clear(&s->u.RSA_private_key.qInv);
1187 load_preshared_secrets(void)
1189 free_preshared_secrets();
1190 (void) process_secrets_file(shared_secrets_file);
1193 /* public key machinery */
1196 public_key_from_rsa(const struct RSA_public_key *k)
1198 struct pubkeyrec *p = alloc_thing(struct pubkeyrec, "pubkeyrec");
1200 p->id = empty_id; /* don't know, doesn't matter */
1202 p->alg = PUBKEY_ALG_RSA;
1205 mpz_init_set(&p->u.rsa.e, &k->e);
1206 mpz_init_set(&p->u.rsa.n, &k->n);
1212 void free_RSA_public_content(struct RSA_public_key *rsa)
1218 /* Free a public key record.
1219 * As a convenience, this returns a pointer to next.
1222 free_public_key(struct pubkeyrec *p)
1224 struct pubkeyrec *nxt = p->next;
1226 free_id_content(&p->id);
1228 /* algorithm-specific freeing */
1231 case PUBKEY_ALG_RSA:
1232 free_RSA_public_content(&p->u.rsa);
1243 free_public_keys(struct pubkeyrec **keys)
1245 while (*keys != NULL)
1246 *keys = free_public_key(*keys);
1249 /* root of chained public key list */
1251 struct pubkeyrec *pubkeys = NULL; /* keys from ipsec.conf */
1254 free_remembered_public_keys(void)
1256 free_public_keys(&pubkeys);
1259 /* transfer public keys from *keys list to front of pubkeys list */
1261 remember_public_keys(struct pubkeyrec **keys)
1263 struct pubkeyrec **pp = keys;
1272 /* decode of RSA pubkey chunk
1273 * - format specified in RFC 2537 RSA/MD5 Keys and SIGs in the DNS
1274 * - exponent length in bytes (1 or 3 octets)
1275 * + 1 byte if in [1, 255]
1276 * + otherwise 0x00 followed by 2 bytes of length
1281 unpack_RSA_public_key(struct RSA_public_key *rsa, chunk_t *pubkey)
1286 rsa->keyid[0] = '\0'; /* in case of keybolbtoid failure */
1288 if (pubkey->len < 3)
1289 return "RSA public key blob way to short"; /* not even room for length! */
1291 if (pubkey->ptr[0] != 0x00)
1293 setchunk(exp, pubkey->ptr + 1, pubkey->ptr[0]);
1297 setchunk(exp, pubkey->ptr + 3
1298 , (pubkey->ptr[1] << BITS_PER_BYTE) + pubkey->ptr[2]);
1301 if (pubkey->len - (exp.ptr - pubkey->ptr) < exp.len + RSA_MIN_OCTETS_RFC)
1302 return "RSA public key blob too short";
1304 mod.ptr = exp.ptr + exp.len;
1305 mod.len = &pubkey->ptr[pubkey->len] - mod.ptr;
1307 if (mod.len < RSA_MIN_OCTETS)
1308 return RSA_MIN_OCTETS_UGH;
1310 if (mod.len > RSA_MAX_OCTETS)
1311 return RSA_MAX_OCTETS_UGH;
1313 n_to_mpz(&rsa->e, exp.ptr, exp.len);
1314 n_to_mpz(&rsa->n, mod.ptr, mod.len);
1316 keyblobtoid(pubkey->ptr, pubkey->len, rsa->keyid, sizeof(rsa->keyid));
1319 DBG(DBG_PRIVATE, RSA_show_public_key(rsa));
1323 rsa->k = mpz_sizeinbase(&rsa->n, 2); /* size in bits, for a start */
1324 rsa->k = (rsa->k + BITS_PER_BYTE - 1) / BITS_PER_BYTE; /* now octets */
1326 if (rsa->k != mod.len)
1330 return "RSA modulus shorter than specified";
1337 same_RSA_public_key(const struct RSA_public_key *a
1338 , const struct RSA_public_key *b)
1341 || (a->k == b->k && mpz_cmp(&a->n, &b->n) == 0 && mpz_cmp(&a->e, &b->e) == 0);
1346 install_public_key(struct pubkeyrec *p, struct pubkeyrec **head)
1348 unshare_id_content(&p->id);
1350 /* store the time the public key was installed */
1351 time(&p->installed);
1353 /* install new key at front */
1360 delete_public_keys(const struct id *id, enum pubkey_alg alg)
1362 struct pubkeyrec **pp, *p;
1364 for (pp = &pubkeys; (p = *pp) != NULL; )
1366 if (same_id(id, &p->id) && p->alg == alg)
1367 *pp = free_public_key(p);
1374 add_public_key(const struct id *id
1375 , enum dns_auth_level dns_auth_level
1376 , enum pubkey_alg alg
1378 , struct pubkeyrec **head)
1380 struct pubkeyrec *p = alloc_thing(struct pubkeyrec, "pubkeyrec");
1382 /* first: algorithm-specific decoding of key chunk */
1385 case PUBKEY_ALG_RSA:
1387 err_t ugh = unpack_RSA_public_key(&p->u.rsa, key);
1401 p->dns_auth_level = dns_auth_level;
1403 p->until = UNDEFINED_TIME;
1404 install_public_key(p, head);
1408 /* extract id and public key from x.509 certificate and insert it
1412 add_x509_public_key(const x509cert_t *cert , enum dns_auth_level dns_auth_level)
1415 struct pubkeyrec *p;
1417 /* we support RSA only */
1418 if (cert->subjectPublicKeyAlgorithm != PUBKEY_ALG_RSA) return;
1420 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1421 p = allocate_RSA_public_key(cert);
1422 p->id.kind = ID_DER_ASN1_DN;
1423 p->id.name = cert->subject;
1424 p->dns_auth_level = dns_auth_level;
1425 p->until = cert->notAfter;
1426 delete_public_keys(&p->id, p->alg);
1427 install_public_key(p, &pubkeys);
1429 gn = cert->subjectAltName;
1431 while (gn != NULL) /* insert all subjectAltNames */
1433 struct id id = empty_id;
1436 if (id.kind != ID_NONE)
1438 p = allocate_RSA_public_key(cert);
1440 p->dns_auth_level = dns_auth_level;
1441 p->until = cert->notAfter;
1442 delete_public_keys(&p->id, p->alg);
1443 install_public_key(p, &pubkeys);
1449 /* when a X.509 certificate gets revoked, all instances of
1450 * the corresponding public key must be removed
1453 remove_x509_public_key(const x509cert_t *cert)
1455 struct pubkeyrec *p, **pp, *revoked_p;
1457 revoked_p = allocate_RSA_public_key(cert);
1463 if (same_RSA_public_key(&p->u.rsa, &revoked_p->u.rsa))
1465 /* remove p from list and free memory */
1466 *pp = free_public_key(p);
1467 loglog(RC_LOG_SERIOUS,
1468 "revoked RSA public key deleted");
1476 free_public_key(revoked_p);
1480 * list all public keys in the chained list
1482 void list_public_keys(bool utc)
1484 struct pubkeyrec *p = pubkeys;
1486 whack_log(RC_COMMENT, " ");
1487 whack_log(RC_COMMENT, "List of Public Keys:");
1488 whack_log(RC_COMMENT, " ");
1492 if (p->alg == PUBKEY_ALG_RSA)
1494 char id_buf[IDTOA_BUF];
1495 char expires_buf[TIMETOA_BUF];
1497 idtoa(&p->id, id_buf, IDTOA_BUF);
1498 strcpy(expires_buf, timetoa(&p->until, utc));
1500 whack_log(RC_COMMENT, "%s, %4d RSA Key %s, until %s %s",
1501 timetoa(&p->installed, utc), 8*p->u.rsa.k, p->u.rsa.keyid,
1503 check_expiry(p->until, PUBKEY_WARNING_INTERVAL, TRUE));
1504 whack_log(RC_COMMENT," %s '%s'",
1505 enum_show(&ident_names, p->id.kind), id_buf);