pluto: Drop support for legacy PSK format.
[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 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <time.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <resolv.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29
30 #ifdef HAVE_GLOB_H
31 #include <glob.h>
32 #ifndef GLOB_ABORTED
33 # define GLOB_ABORTED GLOB_ABEND /* fix for old versions */
34 #endif
35 #endif
36
37 #include <freeswan.h>
38
39 #include <library.h>
40 #include <asn1/asn1.h>
41 #include <credentials/certificates/pgp_certificate.h>
42 #include <credentials/sets/mem_cred.h>
43 #include <credentials/sets/callback_cred.h>
44
45 #include "constants.h"
46 #include "defs.h"
47 #include "x509.h"
48 #include "certs.h"
49 #include "smartcard.h"
50 #include "connections.h"
51 #include "state.h"
52 #include "lex.h"
53 #include "keys.h"
54 #include "adns.h" /* needs <resolv.h> */
55 #include "dnskey.h" /* needs keys.h and adns.h */
56 #include "log.h"
57 #include "whack.h" /* for RC_LOG_SERIOUS */
58 #include "timer.h"
59 #include "fetch.h"
60
61 const char *shared_secrets_file = SHARED_SECRETS_FILE;
62
63
64 typedef enum secret_kind_t secret_kind_t;
65
66 enum secret_kind_t {
67 SECRET_PSK,
68 SECRET_PUBKEY,
69 SECRET_XAUTH,
70 SECRET_PIN
71 };
72
73 typedef struct secret_t secret_t;
74
75 struct secret_t {
76 linked_list_t *ids;
77 secret_kind_t kind;
78 union {
79 chunk_t preshared_secret;
80 private_key_t *private_key;
81 smartcard_t *smartcard;
82 } u;
83 secret_t *next;
84 };
85
86 /*
87 * free a public key struct
88 */
89 static void free_public_key(pubkey_t *pk)
90 {
91 DESTROY_IF(pk->id);
92 DESTROY_IF(pk->public_key);
93 DESTROY_IF(pk->issuer);
94 free(pk->serial.ptr);
95 free(pk);
96 }
97
98 secret_t *secrets = NULL;
99
100 /**
101 * Find the secret associated with the combination of me and the peer.
102 */
103 const secret_t* match_secret(identification_t *my_id, identification_t *his_id,
104 secret_kind_t kind)
105 {
106 enum { /* bits */
107 match_default = 0x01,
108 match_him = 0x02,
109 match_me = 0x04
110 };
111
112 unsigned int best_match = 0;
113 secret_t *s, *best = NULL;
114
115 for (s = secrets; s != NULL; s = s->next)
116 {
117 unsigned int match = 0;
118
119 if (s->kind != kind)
120 {
121 continue;
122 }
123
124 if (s->ids->get_count(s->ids) == 0)
125 {
126 /* a default (signified by lack of ids):
127 * accept if no more specific match found
128 */
129 match = match_default;
130 }
131 else
132 {
133 /* check if both ends match ids */
134 enumerator_t *enumerator;
135 identification_t *id;
136
137 enumerator = s->ids->create_enumerator(s->ids);
138 while (enumerator->enumerate(enumerator, &id))
139 {
140 if (my_id->equals(my_id, id))
141 {
142 match |= match_me;
143 }
144 if (his_id->equals(his_id, id))
145 {
146 match |= match_him;
147 }
148 }
149 enumerator->destroy(enumerator);
150
151 /* If our end matched the only id in the list,
152 * default to matching any peer.
153 * A more specific match will trump this.
154 */
155 if (match == match_me && s->ids->get_count(s->ids) == 1)
156 {
157 match |= match_default;
158 }
159 }
160
161 switch (match)
162 {
163 case match_me:
164 /* if this is an asymmetric (eg. public key) system,
165 * allow this-side-only match to count, even if
166 * there are other ids in the list.
167 */
168 if (kind != SECRET_PUBKEY)
169 {
170 break;
171 }
172 /* FALLTHROUGH */
173 case match_default: /* default all */
174 case match_me | match_default: /* default peer */
175 case match_me | match_him: /* explicit */
176 if (match == best_match)
177 {
178 /* two good matches are equally good: do they agree? */
179 bool same = FALSE;
180
181 switch (kind)
182 {
183 case SECRET_PSK:
184 case SECRET_XAUTH:
185 same = chunk_equals(s->u.preshared_secret,
186 best->u.preshared_secret);
187 break;
188 case SECRET_PUBKEY:
189 same = s->u.private_key->equals(s->u.private_key,
190 best->u.private_key);
191 break;
192 default:
193 bad_case(kind);
194 }
195 if (!same)
196 {
197 loglog(RC_LOG_SERIOUS, "multiple ipsec.secrets entries with "
198 "distinct secrets match endpoints: first secret used");
199 best = s; /* list is backwards: take latest in list */
200 }
201 }
202 else if (match > best_match)
203 {
204 /* this is the best match so far */
205 best_match = match;
206 best = s;
207 }
208 }
209 }
210 return best;
211 }
212
213 /**
214 * Retrieves an XAUTH secret primarily based on the user ID and
215 * secondarily based on the server ID
216 */
217 bool get_xauth_secret(identification_t *user, identification_t *server,
218 chunk_t *secret)
219 {
220 const secret_t *s;
221
222 s = match_secret(user, server, SECRET_XAUTH);
223 if (s)
224 {
225 *secret = chunk_clone(s->u.preshared_secret);
226 return TRUE;
227 }
228 else
229 {
230 *secret = chunk_empty;
231 return FALSE;
232 }
233 }
234
235 /**
236 * We match the ID (if none, the IP address). Failure is indicated by a NULL.
237 */
238 static const secret_t* get_secret(const connection_t *c, secret_kind_t kind)
239 {
240 identification_t *my_id, *his_id;
241 const secret_t *best;
242
243 my_id = c->spd.this.id;
244
245 if (his_id_was_instantiated(c))
246 {
247 /* roadwarrior: replace him with 0.0.0.0 */
248 his_id = identification_create_from_string("%any");
249 }
250 else if (kind == SECRET_PSK && (c->policy & (POLICY_PSK | POLICY_XAUTH_PSK)) &&
251 ((c->kind == CK_TEMPLATE &&
252 c->spd.that.id->get_type(c->spd.that.id) == ID_ANY) ||
253 (c->kind == CK_INSTANCE && id_is_ipaddr(c->spd.that.id))))
254 {
255 /* roadwarrior: replace him with 0.0.0.0 */
256 his_id = identification_create_from_string("%any");
257 }
258 else
259 {
260 his_id = c->spd.that.id->clone(c->spd.that.id);
261 }
262
263 best = match_secret(my_id, his_id, kind);
264
265 his_id->destroy(his_id);
266 return best;
267 }
268
269 /* find the appropriate preshared key (see get_secret).
270 * Failure is indicated by a NULL pointer.
271 * Note: the result is not to be freed by the caller.
272 */
273 const chunk_t* get_preshared_secret(const connection_t *c)
274 {
275 const secret_t *s = get_secret(c, SECRET_PSK);
276
277 DBG(DBG_PRIVATE,
278 if (s == NULL)
279 DBG_log("no Preshared Key Found");
280 else
281 DBG_dump_chunk("Preshared Key", s->u.preshared_secret);
282 )
283 return s == NULL? NULL : &s->u.preshared_secret;
284 }
285
286 /* check the existence of a private key matching a public key contained
287 * in an X.509 or OpenPGP certificate
288 */
289 bool has_private_key(cert_t *cert)
290 {
291 secret_t *s;
292 bool has_key = FALSE;
293 public_key_t *pub_key = cert->cert->get_public_key(cert->cert);
294
295 for (s = secrets; s != NULL; s = s->next)
296 {
297 if (s->kind == SECRET_PUBKEY &&
298 s->u.private_key->belongs_to(s->u.private_key, pub_key))
299 {
300 has_key = TRUE;
301 break;
302 }
303 }
304 pub_key->destroy(pub_key);
305 return has_key;
306 }
307
308 /*
309 * get the matching private key belonging to a given X.509 certificate
310 */
311 private_key_t* get_x509_private_key(const cert_t *cert)
312 {
313 public_key_t *public_key = cert->cert->get_public_key(cert->cert);
314 private_key_t *private_key = NULL;
315 secret_t *s;
316
317 for (s = secrets; s != NULL; s = s->next)
318 {
319
320 if (s->kind == SECRET_PUBKEY &&
321 s->u.private_key->belongs_to(s->u.private_key, public_key))
322 {
323 private_key = s->u.private_key;
324 break;
325 }
326 }
327 public_key->destroy(public_key);
328 return private_key;
329 }
330
331 /* find the appropriate private key (see get_secret).
332 * Failure is indicated by a NULL pointer.
333 */
334 private_key_t* get_private_key(const connection_t *c)
335 {
336 const secret_t *s, *best = NULL;
337
338 /* is a certificate assigned to this connection? */
339 if (c->spd.this.cert)
340 {
341 certificate_t *certificate;
342 public_key_t *pub_key;
343
344 certificate = c->spd.this.cert->cert;
345 pub_key = certificate->get_public_key(certificate);
346
347 for (s = secrets; s != NULL; s = s->next)
348 {
349 if (s->kind == SECRET_PUBKEY &&
350 s->u.private_key->belongs_to(s->u.private_key, pub_key))
351 {
352 best = s;
353 break; /* found the private key - no sense in searching further */
354 }
355 }
356 pub_key->destroy(pub_key);
357 }
358 else
359 {
360 best = get_secret(c, SECRET_PUBKEY);
361 }
362 return best ? best->u.private_key : NULL;
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 process_psk_secret(chunk_t *psk)
406 {
407 err_t ugh = NULL;
408
409 if (*tok == '"' || *tok == '\'')
410 {
411 chunk_t secret = { tok + 1, flp->cur - tok -2 };
412
413 *psk = chunk_clone(secret);
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 chunk_t secret = { buf, sz };
431 *psk = chunk_clone(secret);
432 (void) shift();
433 }
434 }
435 return ugh;
436 }
437
438 typedef enum rsa_private_key_part_t rsa_private_key_part_t;
439
440 enum rsa_private_key_part_t {
441 RSA_PART_MODULUS = 0,
442 RSA_PART_PUBLIC_EXPONENT = 1,
443 RSA_PART_PRIVATE_EXPONENT = 2,
444 RSA_PART_PRIME1 = 3,
445 RSA_PART_PRIME2 = 4,
446 RSA_PART_EXPONENT1 = 5,
447 RSA_PART_EXPONENT2 = 6,
448 RSA_PART_COEFFICIENT = 7
449 };
450
451 const char *rsa_private_key_part_names[] = {
452 "Modulus",
453 "PublicExponent",
454 "PrivateExponent",
455 "Prime1",
456 "Prime2",
457 "Exponent1",
458 "Exponent2",
459 "Coefficient"
460 };
461
462 /**
463 * Parse fields of an RSA private key in BIND 8.2's representation
464 * consistiong of a braced list of keyword and value pairs in required order.
465 */
466 static err_t process_rsa_secret(private_key_t **key)
467 {
468 chunk_t rsa_chunk[countof(rsa_private_key_part_names)];
469 u_char buf[RSA_MAX_ENCODING_BYTES]; /* limit on size of binary representation of key */
470 rsa_private_key_part_t part, p;
471 size_t sz;
472 err_t ugh;
473
474 for (part = RSA_PART_MODULUS; part <= RSA_PART_COEFFICIENT; part++)
475 {
476 const char *keyword = rsa_private_key_part_names[part];
477
478 if (!shift())
479 {
480 ugh = "premature end of RSA key";
481 goto end;
482 }
483 if (!tokeqword(keyword))
484 {
485 ugh = builddiag("%s keyword not found where expected in RSA key"
486 , keyword);
487 goto end;
488 }
489 if (!(shift() && (!tokeq(":") || shift()))) /* ignore optional ":" */
490 {
491 ugh = "premature end of RSA key";
492 goto end;
493 }
494 ugh = ttodatav(tok, flp->cur - tok, 0, buf, sizeof(buf), &sz,
495 diag_space, sizeof(diag_space), TTODATAV_SPACECOUNTS);
496 if (ugh)
497 {
498 ugh = builddiag("RSA data malformed (%s): %s", ugh, tok);
499 goto end;
500 }
501 rsa_chunk[part] = chunk_create(buf, sz);
502 rsa_chunk[part] = chunk_clone(rsa_chunk[part]);
503 }
504
505 /* We require an (indented) '}' and the end of the record.
506 * We break down the test so that the diagnostic will be more helpful.
507 * Some people don't seem to wish to indent the brace!
508 */
509 if (!shift() || !tokeq("}"))
510 {
511 ugh = "malformed end of RSA private key -- indented '}' required";
512 goto end;
513 }
514 if (shift())
515 {
516 ugh = "malformed end of RSA private key -- unexpected token after '}'";
517 goto end;
518 }
519
520 *key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
521 BUILD_RSA_MODULUS, rsa_chunk[RSA_PART_MODULUS],
522 BUILD_RSA_PUB_EXP, rsa_chunk[RSA_PART_PUBLIC_EXPONENT],
523 BUILD_RSA_PRIV_EXP, rsa_chunk[RSA_PART_PRIVATE_EXPONENT],
524 BUILD_RSA_PRIME1, rsa_chunk[RSA_PART_PRIME1],
525 BUILD_RSA_PRIME2, rsa_chunk[RSA_PART_PRIME2],
526 BUILD_RSA_EXP1, rsa_chunk[RSA_PART_EXPONENT1],
527 BUILD_RSA_EXP2, rsa_chunk[RSA_PART_EXPONENT2],
528 BUILD_RSA_COEFF, rsa_chunk[RSA_PART_COEFFICIENT],
529 BUILD_END);
530
531 if (*key == NULL)
532 {
533 ugh = "parsing of RSA private key failed";
534 }
535
536 end:
537 /* clean up and return */
538 for (p = RSA_PART_MODULUS ; p < part; p++)
539 {
540 chunk_clear(&rsa_chunk[p]);
541 }
542 return ugh;
543 }
544
545 /* struct used to prompt for a secret passphrase
546 * from a console with file descriptor fd
547 */
548 typedef struct {
549 char secret[PROMPT_PASS_LEN+1];
550 bool prompt;
551 int fd;
552 int try;
553 } prompt_pass_t;
554
555 /**
556 * Passphrase callback to read from whack fd
557 */
558 static shared_key_t* whack_pass_cb(prompt_pass_t *pass, shared_key_type_t type,
559 identification_t *me, identification_t *other,
560 id_match_t *match_me, id_match_t *match_other)
561 {
562 int n;
563
564 if (type != SHARED_ANY && type != SHARED_PRIVATE_KEY_PASS)
565 {
566 return NULL;
567 }
568
569 if (pass->try > MAX_PROMPT_PASS_TRIALS)
570 {
571 whack_log(RC_LOG_SERIOUS, "invalid passphrase, too many trials");
572 return NULL;
573 }
574 if (pass->try == 1)
575 {
576 whack_log(RC_ENTERSECRET, "need passphrase for 'private key'");
577 }
578 else
579 {
580 whack_log(RC_ENTERSECRET, "invalid passphrase, please try again");
581 }
582 pass->try++;
583
584 n = read(pass->fd, pass->secret, PROMPT_PASS_LEN);
585 if (n == -1)
586 {
587 whack_log(RC_LOG_SERIOUS, "read(whackfd) failed");
588 return NULL;
589 }
590 pass->secret[n-1] = '\0';
591
592 if (strlen(pass->secret) == 0)
593 {
594 whack_log(RC_LOG_SERIOUS, "no passphrase entered, aborted");
595 return NULL;
596 }
597 if (match_me)
598 {
599 *match_me = ID_MATCH_PERFECT;
600 }
601 if (match_other)
602 {
603 *match_other = ID_MATCH_NONE;
604 }
605 return shared_key_create(SHARED_PRIVATE_KEY_PASS,
606 chunk_clone(chunk_create(pass->secret, strlen(pass->secret))));
607 }
608
609 /**
610 * Loads a PKCS#1 or PGP private key file
611 */
612 static private_key_t* load_private_key(char* filename, prompt_pass_t *pass,
613 key_type_t type)
614 {
615 private_key_t *key = NULL;
616 char *path;
617
618 path = concatenate_paths(PRIVATE_KEY_PATH, filename);
619 if (pass && pass->prompt && pass->fd != NULL_FD)
620 { /* use passphrase callback */
621 callback_cred_t *cb;
622
623 cb = callback_cred_create_shared((void*)whack_pass_cb, pass);
624 lib->credmgr->add_local_set(lib->credmgr, &cb->set);
625
626 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
627 BUILD_FROM_FILE, path, BUILD_END);
628 lib->credmgr->remove_local_set(lib->credmgr, &cb->set);
629 cb->destroy(cb);
630 if (key)
631 {
632 whack_log(RC_SUCCESS, "valid passphrase");
633 }
634 }
635 else if (pass)
636 { /* use a given passphrase */
637 mem_cred_t *mem;
638 shared_key_t *shared;
639
640 mem = mem_cred_create();
641 lib->credmgr->add_local_set(lib->credmgr, &mem->set);
642 shared = shared_key_create(SHARED_PRIVATE_KEY_PASS,
643 chunk_clone(chunk_create(pass->secret, strlen(pass->secret))));
644 mem->add_shared(mem, shared, NULL);
645 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
646 BUILD_FROM_FILE, path, BUILD_END);
647 lib->credmgr->remove_local_set(lib->credmgr, &mem->set);
648 mem->destroy(mem);
649 }
650 else
651 { /* no passphrase */
652 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
653 BUILD_FROM_FILE, path, BUILD_END);
654
655 }
656 if (key)
657 {
658 plog(" loaded private key from '%s'", filename);
659 }
660 else
661 {
662 plog(" syntax error in private key file");
663 }
664 return key;
665 }
666
667 /**
668 * process a key file protected with optional passphrase which can either be
669 * read from ipsec.secrets or prompted for by using whack
670 */
671 static err_t process_keyfile(private_key_t **key, key_type_t type, int whackfd)
672 {
673 char filename[BUF_LEN];
674 prompt_pass_t pass;
675
676 memset(filename,'\0', BUF_LEN);
677 memset(pass.secret,'\0', sizeof(pass.secret));
678 pass.prompt = FALSE;
679 pass.fd = whackfd;
680 pass.try = 1;
681
682 /* we expect the filename of a PKCS#1 private key file */
683
684 if (*tok == '"' || *tok == '\'') /* quoted filename */
685 memcpy(filename, tok+1, flp->cur - tok - 2);
686 else
687 memcpy(filename, tok, flp->cur - tok);
688
689 if (shift())
690 {
691 /* we expect an appended passphrase or passphrase prompt*/
692 if (tokeqword("%prompt"))
693 {
694 if (pass.fd == NULL_FD)
695 {
696 return "Private key file -- enter passphrase using 'ipsec secrets'";
697 }
698 pass.prompt = TRUE;
699 }
700 else
701 {
702 char *passphrase = tok;
703 size_t len = flp->cur - passphrase;
704
705 if (*tok == '"' || *tok == '\'') /* quoted passphrase */
706 {
707 passphrase++;
708 len -= 2;
709 }
710 if (len > PROMPT_PASS_LEN)
711 {
712 return "Private key file -- passphrase exceeds 64 characters";
713 }
714 memcpy(pass.secret, passphrase, len);
715 }
716 if (shift())
717 {
718 return "Private key file -- unexpected token after passphrase";
719 }
720 }
721 *key = load_private_key(filename, &pass, type);
722
723 return *key ? NULL : "Private key file -- could not be loaded";
724 }
725
726 /**
727 * Process pin read from ipsec.secrets or prompted for it using whack
728 */
729 static err_t process_pin(secret_t *s, int whackfd)
730 {
731 smartcard_t *sc;
732 const char *pin_status = "no pin";
733
734 s->kind = SECRET_PIN;
735
736 /* looking for the smartcard keyword */
737 if (!shift() || strncmp(tok, SCX_TOKEN, strlen(SCX_TOKEN)) != 0)
738 return "PIN keyword must be followed by %smartcard<reader>:<id>";
739
740 sc = scx_add(scx_parse_number_slot_id(tok + strlen(SCX_TOKEN)));
741 s->u.smartcard = sc;
742 scx_share(sc);
743 if (sc->pin.ptr != NULL)
744 {
745 scx_release_context(sc);
746 scx_free_pin(&sc->pin);
747 }
748 sc->valid = FALSE;
749
750 if (!shift())
751 return "PIN statement must be terminated either by <pin code>, %pinpad or %prompt";
752
753 if (tokeqword("%prompt"))
754 {
755 shift();
756 /* if whackfd exists, whack will be used to prompt for a pin */
757 if (whackfd != NULL_FD)
758 pin_status = scx_get_pin(sc, whackfd) ? "valid pin" : "invalid pin";
759 else
760 pin_status = "pin entry via prompt";
761 }
762 else if (tokeqword("%pinpad"))
763 {
764 chunk_t empty_pin = { "", 0 };
765
766 shift();
767
768 /* pin will be entered via pin pad during verification */
769 sc->pin = chunk_clone(empty_pin);
770 sc->pinpad = TRUE;
771 sc->valid = TRUE;
772 pin_status = "pin entry via pad";
773 if (pkcs11_keep_state)
774 {
775 scx_verify_pin(sc);
776 }
777 }
778 else
779 {
780 /* we read the pin directly from ipsec.secrets */
781 err_t ugh = process_psk_secret(&sc->pin);
782 if (ugh != NULL)
783 return ugh;
784 /* verify the pin */
785 pin_status = scx_verify_pin(sc) ? "valid PIN" : "invalid PIN";
786 }
787 #ifdef SMARTCARD
788 {
789 char buf[BUF_LEN];
790
791 if (sc->any_slot)
792 snprintf(buf, BUF_LEN, "any slot");
793 else
794 snprintf(buf, BUF_LEN, "slot: %lu", sc->slot);
795
796 plog(" %s for #%d (%s, id: %s)"
797 , pin_status, sc->number, scx_print_slot(sc, ""), sc->id);
798 }
799 #else
800 plog(" warning: SMARTCARD support is deactivated in pluto/Makefile!");
801 #endif
802 return NULL;
803 }
804
805 static void log_psk(char *label, secret_t *s)
806 {
807 int n = 0;
808 char buf[BUF_LEN];
809 enumerator_t *enumerator;
810 identification_t *id;
811
812 if (s->ids->get_count(s->ids) == 0)
813 {
814 n = snprintf(buf, BUF_LEN, "%%any");
815 }
816 else
817 {
818 enumerator = s->ids->create_enumerator(s->ids);
819 while(enumerator->enumerate(enumerator, &id))
820 {
821 n += snprintf(buf + n, BUF_LEN - n, "%Y ", id);
822 if (n >= BUF_LEN)
823 {
824 n = BUF_LEN - 1;
825 break;
826 }
827 }
828 enumerator->destroy(enumerator);
829 }
830 plog(" loaded %s secret for %.*s", label, n, buf);
831 }
832
833 static void process_secret(secret_t *s, int whackfd)
834 {
835 err_t ugh = NULL;
836
837 s->kind = SECRET_PSK; /* default */
838 if (tokeqword("psk"))
839 {
840 log_psk("PSK", s);
841
842 /* preshared key: quoted string or ttodata format */
843 ugh = !shift()? "unexpected end of record in PSK"
844 : process_psk_secret(&s->u.preshared_secret);
845 }
846 else if (tokeqword("xauth"))
847 {
848 s->kind = SECRET_XAUTH;
849 log_psk("XAUTH", s);
850
851 /* xauth secret: quoted string or ttodata format */
852 ugh = !shift()? "unexpected end of record in XAUTH"
853 : process_psk_secret(&s->u.preshared_secret);
854 }
855 else if (tokeqword("rsa"))
856 {
857 /* RSA key: the fun begins.
858 * A braced list of keyword and value pairs.
859 */
860 s->kind = SECRET_PUBKEY;
861 if (!shift())
862 {
863 ugh = "bad RSA key syntax";
864 }
865 else if (tokeq("{"))
866 {
867 ugh = process_rsa_secret(&s->u.private_key);
868 }
869 else
870 {
871 ugh = process_keyfile(&s->u.private_key, KEY_RSA, whackfd);
872 }
873 }
874 else if (tokeqword("ecdsa"))
875 {
876 s->kind = SECRET_PUBKEY;
877 if (!shift())
878 {
879 ugh = "bad ECDSA key syntax";
880 }
881 else
882 {
883 ugh = process_keyfile(&s->u.private_key, KEY_ECDSA, whackfd);
884 }
885 }
886 else if (tokeqword("pin"))
887 {
888 ugh = process_pin(s, whackfd);
889 }
890 else
891 {
892 ugh = builddiag("unrecognized key format: %s", tok);
893 }
894
895 if (ugh != NULL)
896 {
897 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
898 , flp->filename, flp->lino, ugh);
899 s->ids->destroy_offset(s->ids, offsetof(identification_t, destroy));
900 free(s);
901 }
902 else if (flushline("expected record boundary in key"))
903 {
904 /* gauntlet has been run: install new secret */
905 lock_certs_and_keys("process_secret");
906 s->next = secrets;
907 secrets = s;
908 unlock_certs_and_keys("process_secrets");
909 }
910 }
911
912 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
913
914 static void process_secret_records(int whackfd)
915 {
916 /* read records from ipsec.secrets and load them into our table */
917 for (;;)
918 {
919 (void)flushline(NULL); /* silently ditch leftovers, if any */
920 if (flp->bdry == B_file)
921 {
922 break;
923 }
924 flp->bdry = B_none; /* eat the Record Boundary */
925 (void)shift(); /* get real first token */
926
927 if (tokeqword("include"))
928 {
929 /* an include directive */
930 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
931 char *p = fn;
932 char *end_prefix = strrchr(flp->filename, '/');
933
934 if (!shift())
935 {
936 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
937 , flp->filename, flp->lino);
938 continue; /* abandon this record */
939 }
940
941 /* if path is relative and including file's pathname has
942 * a non-empty dirname, prefix this path with that dirname.
943 */
944 if (tok[0] != '/' && end_prefix != NULL)
945 {
946 size_t pl = end_prefix - flp->filename + 1;
947
948 /* "clamp" length to prevent problems now;
949 * will be rediscovered and reported later.
950 */
951 if (pl > sizeof(fn))
952 {
953 pl = sizeof(fn);
954 }
955 memcpy(fn, flp->filename, pl);
956 p += pl;
957 }
958 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
959 {
960 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
961 , flp->filename, flp->lino);
962 continue; /* abandon this record */
963 }
964 strcpy(p, tok);
965 (void) shift(); /* move to Record Boundary, we hope */
966 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
967 {
968 process_secrets_file(fn, whackfd);
969 tok = NULL; /* correct, but probably redundant */
970 }
971 }
972 else
973 {
974 /* expecting a list of indices and then the key info */
975 secret_t *s = malloc_thing(secret_t);
976
977 zero(s);
978 s->ids = linked_list_create();
979 s->kind = SECRET_PSK; /* default */
980 s->u.preshared_secret = chunk_empty;
981 s->next = NULL;
982
983 for (;;)
984 {
985 if (tokeq(":"))
986 {
987 /* found key part */
988 shift(); /* discard explicit separator */
989 process_secret(s, whackfd);
990 break;
991 }
992 else
993 {
994 identification_t *id;
995
996 id = identification_create_from_string(tok);
997 s->ids->insert_last(s->ids, id);
998
999 if (!shift())
1000 {
1001 /* unexpected Record Boundary or EOF */
1002 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end"
1003 " of id list", flp->filename, flp->lino);
1004 s->ids->destroy_offset(s->ids,
1005 offsetof(identification_t, destroy));
1006 free(s);
1007 break;
1008 }
1009 }
1010 }
1011 }
1012 }
1013 }
1014
1015 static int globugh(const char *epath, int eerrno)
1016 {
1017 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
1018 return 1; /* stop glob */
1019 }
1020
1021 static void process_secrets_file(const char *file_pat, int whackfd)
1022 {
1023 struct file_lex_position pos;
1024 char **fnp;
1025
1026 pos.depth = flp == NULL? 0 : flp->depth + 1;
1027
1028 if (pos.depth > 10)
1029 {
1030 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
1031 return;
1032 }
1033
1034 #ifdef HAVE_GLOB_H
1035 /* do globbing */
1036 {
1037 glob_t globbuf;
1038 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1039
1040 if (r != 0)
1041 {
1042 switch (r)
1043 {
1044 case GLOB_NOSPACE:
1045 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1046 break;
1047 case GLOB_ABORTED:
1048 break; /* already logged */
1049 case GLOB_NOMATCH:
1050 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1051 break;
1052 default:
1053 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1054 break;
1055 }
1056 globfree(&globbuf);
1057 return;
1058 }
1059
1060 /* for each file... */
1061 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1062 {
1063 if (lexopen(&pos, *fnp, FALSE))
1064 {
1065 plog("loading secrets from \"%s\"", *fnp);
1066 flushline("file starts with indentation (continuation notation)");
1067 process_secret_records(whackfd);
1068 lexclose();
1069 }
1070 }
1071
1072 globfree(&globbuf);
1073 }
1074 #else /* HAVE_GLOB_H */
1075 /* if glob(3) is not available, try to load pattern directly */
1076 if (lexopen(&pos, file_pat, FALSE))
1077 {
1078 plog("loading secrets from \"%s\"", file_pat);
1079 flushline("file starts with indentation (continuation notation)");
1080 process_secret_records(whackfd);
1081 lexclose();
1082 }
1083 #endif /* HAVE_GLOB_H */
1084 }
1085
1086 void free_preshared_secrets(void)
1087 {
1088 lock_certs_and_keys("free_preshared_secrets");
1089
1090 if (secrets != NULL)
1091 {
1092 secret_t *s, *ns;
1093
1094 plog("forgetting secrets");
1095
1096 for (s = secrets; s != NULL; s = ns)
1097 {
1098 ns = s->next;
1099 s->ids->destroy_offset(s->ids, offsetof(identification_t, destroy));
1100
1101 switch (s->kind)
1102 {
1103 case SECRET_PSK:
1104 case SECRET_XAUTH:
1105 free(s->u.preshared_secret.ptr);
1106 break;
1107 case SECRET_PUBKEY:
1108 DESTROY_IF(s->u.private_key);
1109 break;
1110 case SECRET_PIN:
1111 scx_release(s->u.smartcard);
1112 break;
1113 default:
1114 bad_case(s->kind);
1115 }
1116 free(s);
1117 }
1118 secrets = NULL;
1119 }
1120
1121 unlock_certs_and_keys("free_preshard_secrets");
1122 }
1123
1124 void load_preshared_secrets(int whackfd)
1125 {
1126 free_preshared_secrets();
1127 (void) process_secrets_file(shared_secrets_file, whackfd);
1128 }
1129
1130 /* public key machinery
1131 * Note: caller must set dns_auth_level.
1132 */
1133
1134 pubkey_t* public_key_from_rsa(public_key_t *key)
1135 {
1136 pubkey_t *p = malloc_thing(pubkey_t);
1137
1138 zero(p);
1139 p->id = identification_create_from_string("%any"); /* don't know, doesn't matter */
1140 p->issuer = NULL;
1141 p->serial = chunk_empty;
1142 p->public_key = key;
1143
1144 /* note that we return a 1 reference count upon creation:
1145 * invariant: recount > 0.
1146 */
1147 p->refcnt = 1;
1148 return p;
1149 }
1150
1151 /* Free a public key record.
1152 * As a convenience, this returns a pointer to next.
1153 */
1154 pubkey_list_t* free_public_keyentry(pubkey_list_t *p)
1155 {
1156 pubkey_list_t *nxt = p->next;
1157
1158 if (p->key != NULL)
1159 {
1160 unreference_key(&p->key);
1161 }
1162 free(p);
1163 return nxt;
1164 }
1165
1166 void free_public_keys(pubkey_list_t **keys)
1167 {
1168 while (*keys != NULL)
1169 {
1170 *keys = free_public_keyentry(*keys);
1171 }
1172 }
1173
1174 /* root of chained public key list */
1175
1176 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1177
1178 void free_remembered_public_keys(void)
1179 {
1180 free_public_keys(&pubkeys);
1181 }
1182
1183 /**
1184 * Transfer public keys from *keys list to front of pubkeys list
1185 */
1186 void transfer_to_public_keys(struct gw_info *gateways_from_dns
1187 #ifdef USE_KEYRR
1188 , pubkey_list_t **keys
1189 #endif /* USE_KEYRR */
1190 )
1191 {
1192 {
1193 struct gw_info *gwp;
1194
1195 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1196 {
1197 pubkey_list_t *pl = malloc_thing(pubkey_list_t);
1198
1199 pl->key = gwp->key; /* note: this is a transfer */
1200 gwp->key = NULL; /* really, it is! */
1201 pl->next = pubkeys;
1202 pubkeys = pl;
1203 }
1204 }
1205
1206 #ifdef USE_KEYRR
1207 {
1208 pubkey_list_t **pp = keys;
1209
1210 while (*pp != NULL)
1211 {
1212 pp = &(*pp)->next;
1213 }
1214 *pp = pubkeys;
1215 pubkeys = *keys;
1216 *keys = NULL;
1217 }
1218 #endif /* USE_KEYRR */
1219 }
1220
1221
1222 static void install_public_key(pubkey_t *pk, pubkey_list_t **head)
1223 {
1224 pubkey_list_t *p = malloc_thing(pubkey_list_t);
1225
1226 /* install new key at front */
1227 p->key = reference_key(pk);
1228 p->next = *head;
1229 *head = p;
1230 }
1231
1232 void delete_public_keys(identification_t *id, key_type_t type,
1233 identification_t *issuer, chunk_t serial)
1234 {
1235 pubkey_list_t **pp, *p;
1236 pubkey_t *pk;
1237 key_type_t pk_type;
1238
1239 for (pp = &pubkeys; (p = *pp) != NULL; )
1240 {
1241 pk = p->key;
1242 pk_type = pk->public_key->get_type(pk->public_key);
1243
1244 if (id->equals(id, pk->id) && pk_type == type
1245 && (issuer == NULL || pk->issuer == NULL
1246 || issuer->equals(issuer, pk->issuer))
1247 && (serial.ptr == NULL || chunk_equals(serial, pk->serial)))
1248 {
1249 *pp = free_public_keyentry(p);
1250 }
1251 else
1252 {
1253 pp = &p->next;
1254 }
1255 }
1256 }
1257
1258 pubkey_t* reference_key(pubkey_t *pk)
1259 {
1260 DBG(DBG_CONTROLMORE,
1261 DBG_log(" ref key: %p %p cnt %d '%Y'",
1262 pk, pk->public_key, pk->refcnt, pk->id)
1263 )
1264 pk->refcnt++;
1265 return pk;
1266 }
1267
1268 void unreference_key(pubkey_t **pkp)
1269 {
1270 pubkey_t *pk = *pkp;
1271
1272 if (pk == NULL)
1273 {
1274 return;
1275 }
1276
1277 DBG(DBG_CONTROLMORE,
1278 DBG_log("unref key: %p %p cnt %d '%Y'",
1279 pk, pk->public_key, pk->refcnt, pk->id)
1280 )
1281
1282 /* cancel out the pointer */
1283 *pkp = NULL;
1284
1285 passert(pk->refcnt != 0);
1286 pk->refcnt--;
1287 if (pk->refcnt == 0)
1288 {
1289 free_public_key(pk);
1290 }
1291 }
1292
1293 bool add_public_key(identification_t *id, enum dns_auth_level dns_auth_level,
1294 enum pubkey_alg alg, chunk_t rfc3110_key,
1295 pubkey_list_t **head)
1296 {
1297 public_key_t *key = NULL;
1298 pubkey_t *pk;
1299
1300 /* first: algorithm-specific decoding of key chunk */
1301 switch (alg)
1302 {
1303 case PUBKEY_ALG_RSA:
1304 key = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
1305 BUILD_BLOB_DNSKEY, rfc3110_key,
1306 BUILD_END);
1307 if (key == NULL)
1308 {
1309 return FALSE;
1310 }
1311 break;
1312 default:
1313 bad_case(alg);
1314 }
1315
1316 pk = malloc_thing(pubkey_t);
1317 zero(pk);
1318 pk->public_key = key;
1319 pk->id = id->clone(id);
1320 pk->dns_auth_level = dns_auth_level;
1321 pk->until_time = UNDEFINED_TIME;
1322 pk->issuer = NULL;
1323 pk->serial = chunk_empty;
1324 install_public_key(pk, head);
1325 return TRUE;
1326 }
1327
1328 /**
1329 * Extract id and public key a certificate and insert it into a pubkeyrec
1330 */
1331 void add_public_key_from_cert(cert_t *cert , time_t until,
1332 enum dns_auth_level dns_auth_level)
1333 {
1334 certificate_t *certificate = cert->cert;
1335 identification_t *subject = certificate->get_subject(certificate);
1336 identification_t *issuer = NULL;
1337 identification_t *id;
1338 chunk_t serialNumber = chunk_empty;
1339 pubkey_t *pk;
1340 key_type_t pk_type;
1341
1342 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1343 pk = malloc_thing(pubkey_t);
1344 zero(pk);
1345 pk->public_key = certificate->get_public_key(certificate);
1346 pk_type = pk->public_key->get_type(pk->public_key);
1347 pk->id = subject->clone(subject);
1348 pk->dns_auth_level = dns_auth_level;
1349 pk->until_time = until;
1350 if (certificate->get_type(certificate) == CERT_X509)
1351 {
1352 x509_t *x509 = (x509_t*)certificate;
1353
1354 issuer = certificate->get_issuer(certificate);
1355 serialNumber = x509->get_serial(x509);
1356 pk->issuer = issuer->clone(issuer);
1357 pk->serial = chunk_clone(serialNumber);
1358 }
1359 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1360 install_public_key(pk, &pubkeys);
1361
1362 if (certificate->get_type(certificate) == CERT_X509)
1363 {
1364 x509_t *x509 = (x509_t*)certificate;
1365 enumerator_t *enumerator;
1366
1367 /* insert all subjectAltNames from X.509 certificates */
1368 enumerator = x509->create_subjectAltName_enumerator(x509);
1369 while (enumerator->enumerate(enumerator, &id))
1370 {
1371 if (id->get_type(id) != ID_ANY)
1372 {
1373 pk = malloc_thing(pubkey_t);
1374 zero(pk);
1375 pk->id = id->clone(id);
1376 pk->public_key = certificate->get_public_key(certificate);
1377 pk->dns_auth_level = dns_auth_level;
1378 pk->until_time = until;
1379 pk->issuer = issuer->clone(issuer);
1380 pk->serial = chunk_clone(serialNumber);
1381 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1382 install_public_key(pk, &pubkeys);
1383 }
1384 }
1385 enumerator->destroy(enumerator);
1386 }
1387 else
1388 {
1389 pgp_certificate_t *pgp_cert = (pgp_certificate_t*)certificate;
1390 chunk_t fingerprint = pgp_cert->get_fingerprint(pgp_cert);
1391
1392 /* add v3 or v4 PGP fingerprint */
1393 pk = malloc_thing(pubkey_t);
1394 zero(pk);
1395 pk->id = identification_create_from_encoding(ID_KEY_ID, fingerprint);
1396 pk->public_key = certificate->get_public_key(certificate);
1397 pk->dns_auth_level = dns_auth_level;
1398 pk->until_time = until;
1399 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1400 install_public_key(pk, &pubkeys);
1401 }
1402 }
1403
1404 /* when a X.509 certificate gets revoked, all instances of
1405 * the corresponding public key must be removed
1406 */
1407 void remove_x509_public_key(const cert_t *cert)
1408 {
1409 public_key_t *revoked_key = cert->cert->get_public_key(cert->cert);
1410 pubkey_list_t *p, **pp;
1411
1412 p = pubkeys;
1413 pp = &pubkeys;
1414
1415 while(p != NULL)
1416 {
1417 if (revoked_key->equals(revoked_key, p->key->public_key))
1418 {
1419 /* remove p from list and free memory */
1420 *pp = free_public_keyentry(p);
1421 loglog(RC_LOG_SERIOUS, "invalid public key deleted");
1422 }
1423 else
1424 {
1425 pp = &p->next;
1426 }
1427 p =*pp;
1428 }
1429 revoked_key->destroy(revoked_key);
1430 }
1431
1432 /*
1433 * list all public keys in the chained list
1434 */
1435 void list_public_keys(bool utc)
1436 {
1437 pubkey_list_t *p = pubkeys;
1438
1439 if (p != NULL)
1440 {
1441 whack_log(RC_COMMENT, " ");
1442 whack_log(RC_COMMENT, "List of Public Keys:");
1443 }
1444
1445 while (p != NULL)
1446 {
1447 pubkey_t *key = p->key;
1448 public_key_t *public = key->public_key;
1449 chunk_t keyid;
1450
1451 whack_log(RC_COMMENT, " ");
1452 whack_log(RC_COMMENT, " identity: '%Y'", key->id);
1453 whack_log(RC_COMMENT, " pubkey: %N %4d bits, until %T %s",
1454 key_type_names, public->get_type(public),
1455 public->get_keysize(public),
1456 &key->until_time, utc,
1457 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1458 if (public->get_fingerprint(public, KEYID_PUBKEY_INFO_SHA1, &keyid))
1459 {
1460 whack_log(RC_COMMENT," keyid: %#B", &keyid);
1461 }
1462 if (key->issuer)
1463 {
1464 whack_log(RC_COMMENT," issuer: \"%Y\"", key->issuer);
1465 }
1466 if (key->serial.len)
1467 {
1468 whack_log(RC_COMMENT," serial: %#B", &key->serial);
1469 }
1470 p = p->next;
1471 }
1472 }