a204d86cb909c01e3d15a3759af5b4b602a11a1f
[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 (*tok == '"' || *tok == '\'')
839 {
840 log_psk("PSK", s);
841
842 /* old PSK format: just a string */
843 ugh = process_psk_secret(&s->u.preshared_secret);
844 }
845 else if (tokeqword("psk"))
846 {
847 log_psk("PSK", s);
848
849 /* preshared key: quoted string or ttodata format */
850 ugh = !shift()? "unexpected end of record in PSK"
851 : process_psk_secret(&s->u.preshared_secret);
852 }
853 else if (tokeqword("xauth"))
854 {
855 s->kind = SECRET_XAUTH;
856 log_psk("XAUTH", s);
857
858 /* xauth secret: quoted string or ttodata format */
859 ugh = !shift()? "unexpected end of record in XAUTH"
860 : process_psk_secret(&s->u.preshared_secret);
861 }
862 else if (tokeqword("rsa"))
863 {
864 /* RSA key: the fun begins.
865 * A braced list of keyword and value pairs.
866 */
867 s->kind = SECRET_PUBKEY;
868 if (!shift())
869 {
870 ugh = "bad RSA key syntax";
871 }
872 else if (tokeq("{"))
873 {
874 ugh = process_rsa_secret(&s->u.private_key);
875 }
876 else
877 {
878 ugh = process_keyfile(&s->u.private_key, KEY_RSA, whackfd);
879 }
880 }
881 else if (tokeqword("ecdsa"))
882 {
883 s->kind = SECRET_PUBKEY;
884 if (!shift())
885 {
886 ugh = "bad ECDSA key syntax";
887 }
888 else
889 {
890 ugh = process_keyfile(&s->u.private_key, KEY_ECDSA, whackfd);
891 }
892 }
893 else if (tokeqword("pin"))
894 {
895 ugh = process_pin(s, whackfd);
896 }
897 else
898 {
899 ugh = builddiag("unrecognized key format: %s", tok);
900 }
901
902 if (ugh != NULL)
903 {
904 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: %s"
905 , flp->filename, flp->lino, ugh);
906 s->ids->destroy_offset(s->ids, offsetof(identification_t, destroy));
907 free(s);
908 }
909 else if (flushline("expected record boundary in key"))
910 {
911 /* gauntlet has been run: install new secret */
912 lock_certs_and_keys("process_secret");
913 s->next = secrets;
914 secrets = s;
915 unlock_certs_and_keys("process_secrets");
916 }
917 }
918
919 static void process_secrets_file(const char *file_pat, int whackfd); /* forward declaration */
920
921 static void process_secret_records(int whackfd)
922 {
923 /* read records from ipsec.secrets and load them into our table */
924 for (;;)
925 {
926 (void)flushline(NULL); /* silently ditch leftovers, if any */
927 if (flp->bdry == B_file)
928 {
929 break;
930 }
931 flp->bdry = B_none; /* eat the Record Boundary */
932 (void)shift(); /* get real first token */
933
934 if (tokeqword("include"))
935 {
936 /* an include directive */
937 char fn[MAX_TOK_LEN]; /* space for filename (I hope) */
938 char *p = fn;
939 char *end_prefix = strrchr(flp->filename, '/');
940
941 if (!shift())
942 {
943 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end of include directive"
944 , flp->filename, flp->lino);
945 continue; /* abandon this record */
946 }
947
948 /* if path is relative and including file's pathname has
949 * a non-empty dirname, prefix this path with that dirname.
950 */
951 if (tok[0] != '/' && end_prefix != NULL)
952 {
953 size_t pl = end_prefix - flp->filename + 1;
954
955 /* "clamp" length to prevent problems now;
956 * will be rediscovered and reported later.
957 */
958 if (pl > sizeof(fn))
959 {
960 pl = sizeof(fn);
961 }
962 memcpy(fn, flp->filename, pl);
963 p += pl;
964 }
965 if (flp->cur - tok >= &fn[sizeof(fn)] - p)
966 {
967 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: include pathname too long"
968 , flp->filename, flp->lino);
969 continue; /* abandon this record */
970 }
971 strcpy(p, tok);
972 (void) shift(); /* move to Record Boundary, we hope */
973 if (flushline("ignoring malformed INCLUDE -- expected Record Boundary after filename"))
974 {
975 process_secrets_file(fn, whackfd);
976 tok = NULL; /* correct, but probably redundant */
977 }
978 }
979 else
980 {
981 /* expecting a list of indices and then the key info */
982 secret_t *s = malloc_thing(secret_t);
983
984 zero(s);
985 s->ids = linked_list_create();
986 s->kind = SECRET_PSK; /* default */
987 s->u.preshared_secret = chunk_empty;
988 s->next = NULL;
989
990 for (;;)
991 {
992 if (tok[0] == '"' || tok[0] == '\'')
993 {
994 /* found key part */
995 process_secret(s, whackfd);
996 break;
997 }
998 else if (tokeq(":"))
999 {
1000 /* found key part */
1001 shift(); /* discard explicit separator */
1002 process_secret(s, whackfd);
1003 break;
1004 }
1005 else
1006 {
1007 identification_t *id;
1008
1009 id = identification_create_from_string(tok);
1010 s->ids->insert_last(s->ids, id);
1011
1012 if (!shift())
1013 {
1014 /* unexpected Record Boundary or EOF */
1015 loglog(RC_LOG_SERIOUS, "\"%s\" line %d: unexpected end"
1016 " of id list", flp->filename, flp->lino);
1017 s->ids->destroy_offset(s->ids,
1018 offsetof(identification_t, destroy));
1019 free(s);
1020 break;
1021 }
1022 }
1023 }
1024 }
1025 }
1026 }
1027
1028 static int globugh(const char *epath, int eerrno)
1029 {
1030 log_errno_routine(eerrno, "problem with secrets file \"%s\"", epath);
1031 return 1; /* stop glob */
1032 }
1033
1034 static void process_secrets_file(const char *file_pat, int whackfd)
1035 {
1036 struct file_lex_position pos;
1037 char **fnp;
1038
1039 pos.depth = flp == NULL? 0 : flp->depth + 1;
1040
1041 if (pos.depth > 10)
1042 {
1043 loglog(RC_LOG_SERIOUS, "preshared secrets file \"%s\" nested too deeply", file_pat);
1044 return;
1045 }
1046
1047 #ifdef HAVE_GLOB_H
1048 /* do globbing */
1049 {
1050 glob_t globbuf;
1051 int r = glob(file_pat, GLOB_ERR, globugh, &globbuf);
1052
1053 if (r != 0)
1054 {
1055 switch (r)
1056 {
1057 case GLOB_NOSPACE:
1058 loglog(RC_LOG_SERIOUS, "out of space processing secrets filename \"%s\"", file_pat);
1059 break;
1060 case GLOB_ABORTED:
1061 break; /* already logged */
1062 case GLOB_NOMATCH:
1063 loglog(RC_LOG_SERIOUS, "no secrets filename matched \"%s\"", file_pat);
1064 break;
1065 default:
1066 loglog(RC_LOG_SERIOUS, "unknown glob error %d", r);
1067 break;
1068 }
1069 globfree(&globbuf);
1070 return;
1071 }
1072
1073 /* for each file... */
1074 for (fnp = globbuf.gl_pathv; *fnp != NULL; fnp++)
1075 {
1076 if (lexopen(&pos, *fnp, FALSE))
1077 {
1078 plog("loading secrets from \"%s\"", *fnp);
1079 flushline("file starts with indentation (continuation notation)");
1080 process_secret_records(whackfd);
1081 lexclose();
1082 }
1083 }
1084
1085 globfree(&globbuf);
1086 }
1087 #else /* HAVE_GLOB_H */
1088 /* if glob(3) is not available, try to load pattern directly */
1089 if (lexopen(&pos, file_pat, FALSE))
1090 {
1091 plog("loading secrets from \"%s\"", file_pat);
1092 flushline("file starts with indentation (continuation notation)");
1093 process_secret_records(whackfd);
1094 lexclose();
1095 }
1096 #endif /* HAVE_GLOB_H */
1097 }
1098
1099 void free_preshared_secrets(void)
1100 {
1101 lock_certs_and_keys("free_preshared_secrets");
1102
1103 if (secrets != NULL)
1104 {
1105 secret_t *s, *ns;
1106
1107 plog("forgetting secrets");
1108
1109 for (s = secrets; s != NULL; s = ns)
1110 {
1111 ns = s->next;
1112 s->ids->destroy_offset(s->ids, offsetof(identification_t, destroy));
1113
1114 switch (s->kind)
1115 {
1116 case SECRET_PSK:
1117 case SECRET_XAUTH:
1118 free(s->u.preshared_secret.ptr);
1119 break;
1120 case SECRET_PUBKEY:
1121 DESTROY_IF(s->u.private_key);
1122 break;
1123 case SECRET_PIN:
1124 scx_release(s->u.smartcard);
1125 break;
1126 default:
1127 bad_case(s->kind);
1128 }
1129 free(s);
1130 }
1131 secrets = NULL;
1132 }
1133
1134 unlock_certs_and_keys("free_preshard_secrets");
1135 }
1136
1137 void load_preshared_secrets(int whackfd)
1138 {
1139 free_preshared_secrets();
1140 (void) process_secrets_file(shared_secrets_file, whackfd);
1141 }
1142
1143 /* public key machinery
1144 * Note: caller must set dns_auth_level.
1145 */
1146
1147 pubkey_t* public_key_from_rsa(public_key_t *key)
1148 {
1149 pubkey_t *p = malloc_thing(pubkey_t);
1150
1151 zero(p);
1152 p->id = identification_create_from_string("%any"); /* don't know, doesn't matter */
1153 p->issuer = NULL;
1154 p->serial = chunk_empty;
1155 p->public_key = key;
1156
1157 /* note that we return a 1 reference count upon creation:
1158 * invariant: recount > 0.
1159 */
1160 p->refcnt = 1;
1161 return p;
1162 }
1163
1164 /* Free a public key record.
1165 * As a convenience, this returns a pointer to next.
1166 */
1167 pubkey_list_t* free_public_keyentry(pubkey_list_t *p)
1168 {
1169 pubkey_list_t *nxt = p->next;
1170
1171 if (p->key != NULL)
1172 {
1173 unreference_key(&p->key);
1174 }
1175 free(p);
1176 return nxt;
1177 }
1178
1179 void free_public_keys(pubkey_list_t **keys)
1180 {
1181 while (*keys != NULL)
1182 {
1183 *keys = free_public_keyentry(*keys);
1184 }
1185 }
1186
1187 /* root of chained public key list */
1188
1189 pubkey_list_t *pubkeys = NULL; /* keys from ipsec.conf */
1190
1191 void free_remembered_public_keys(void)
1192 {
1193 free_public_keys(&pubkeys);
1194 }
1195
1196 /**
1197 * Transfer public keys from *keys list to front of pubkeys list
1198 */
1199 void transfer_to_public_keys(struct gw_info *gateways_from_dns
1200 #ifdef USE_KEYRR
1201 , pubkey_list_t **keys
1202 #endif /* USE_KEYRR */
1203 )
1204 {
1205 {
1206 struct gw_info *gwp;
1207
1208 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1209 {
1210 pubkey_list_t *pl = malloc_thing(pubkey_list_t);
1211
1212 pl->key = gwp->key; /* note: this is a transfer */
1213 gwp->key = NULL; /* really, it is! */
1214 pl->next = pubkeys;
1215 pubkeys = pl;
1216 }
1217 }
1218
1219 #ifdef USE_KEYRR
1220 {
1221 pubkey_list_t **pp = keys;
1222
1223 while (*pp != NULL)
1224 {
1225 pp = &(*pp)->next;
1226 }
1227 *pp = pubkeys;
1228 pubkeys = *keys;
1229 *keys = NULL;
1230 }
1231 #endif /* USE_KEYRR */
1232 }
1233
1234
1235 static void install_public_key(pubkey_t *pk, pubkey_list_t **head)
1236 {
1237 pubkey_list_t *p = malloc_thing(pubkey_list_t);
1238
1239 /* install new key at front */
1240 p->key = reference_key(pk);
1241 p->next = *head;
1242 *head = p;
1243 }
1244
1245 void delete_public_keys(identification_t *id, key_type_t type,
1246 identification_t *issuer, chunk_t serial)
1247 {
1248 pubkey_list_t **pp, *p;
1249 pubkey_t *pk;
1250 key_type_t pk_type;
1251
1252 for (pp = &pubkeys; (p = *pp) != NULL; )
1253 {
1254 pk = p->key;
1255 pk_type = pk->public_key->get_type(pk->public_key);
1256
1257 if (id->equals(id, pk->id) && pk_type == type
1258 && (issuer == NULL || pk->issuer == NULL
1259 || issuer->equals(issuer, pk->issuer))
1260 && (serial.ptr == NULL || chunk_equals(serial, pk->serial)))
1261 {
1262 *pp = free_public_keyentry(p);
1263 }
1264 else
1265 {
1266 pp = &p->next;
1267 }
1268 }
1269 }
1270
1271 pubkey_t* reference_key(pubkey_t *pk)
1272 {
1273 DBG(DBG_CONTROLMORE,
1274 DBG_log(" ref key: %p %p cnt %d '%Y'",
1275 pk, pk->public_key, pk->refcnt, pk->id)
1276 )
1277 pk->refcnt++;
1278 return pk;
1279 }
1280
1281 void unreference_key(pubkey_t **pkp)
1282 {
1283 pubkey_t *pk = *pkp;
1284
1285 if (pk == NULL)
1286 {
1287 return;
1288 }
1289
1290 DBG(DBG_CONTROLMORE,
1291 DBG_log("unref key: %p %p cnt %d '%Y'",
1292 pk, pk->public_key, pk->refcnt, pk->id)
1293 )
1294
1295 /* cancel out the pointer */
1296 *pkp = NULL;
1297
1298 passert(pk->refcnt != 0);
1299 pk->refcnt--;
1300 if (pk->refcnt == 0)
1301 {
1302 free_public_key(pk);
1303 }
1304 }
1305
1306 bool add_public_key(identification_t *id, enum dns_auth_level dns_auth_level,
1307 enum pubkey_alg alg, chunk_t rfc3110_key,
1308 pubkey_list_t **head)
1309 {
1310 public_key_t *key = NULL;
1311 pubkey_t *pk;
1312
1313 /* first: algorithm-specific decoding of key chunk */
1314 switch (alg)
1315 {
1316 case PUBKEY_ALG_RSA:
1317 key = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
1318 BUILD_BLOB_DNSKEY, rfc3110_key,
1319 BUILD_END);
1320 if (key == NULL)
1321 {
1322 return FALSE;
1323 }
1324 break;
1325 default:
1326 bad_case(alg);
1327 }
1328
1329 pk = malloc_thing(pubkey_t);
1330 zero(pk);
1331 pk->public_key = key;
1332 pk->id = id->clone(id);
1333 pk->dns_auth_level = dns_auth_level;
1334 pk->until_time = UNDEFINED_TIME;
1335 pk->issuer = NULL;
1336 pk->serial = chunk_empty;
1337 install_public_key(pk, head);
1338 return TRUE;
1339 }
1340
1341 /**
1342 * Extract id and public key a certificate and insert it into a pubkeyrec
1343 */
1344 void add_public_key_from_cert(cert_t *cert , time_t until,
1345 enum dns_auth_level dns_auth_level)
1346 {
1347 certificate_t *certificate = cert->cert;
1348 identification_t *subject = certificate->get_subject(certificate);
1349 identification_t *issuer = NULL;
1350 identification_t *id;
1351 chunk_t serialNumber = chunk_empty;
1352 pubkey_t *pk;
1353 key_type_t pk_type;
1354
1355 /* ID type: ID_DER_ASN1_DN (X.509 subject field) */
1356 pk = malloc_thing(pubkey_t);
1357 zero(pk);
1358 pk->public_key = certificate->get_public_key(certificate);
1359 pk_type = pk->public_key->get_type(pk->public_key);
1360 pk->id = subject->clone(subject);
1361 pk->dns_auth_level = dns_auth_level;
1362 pk->until_time = until;
1363 if (certificate->get_type(certificate) == CERT_X509)
1364 {
1365 x509_t *x509 = (x509_t*)certificate;
1366
1367 issuer = certificate->get_issuer(certificate);
1368 serialNumber = x509->get_serial(x509);
1369 pk->issuer = issuer->clone(issuer);
1370 pk->serial = chunk_clone(serialNumber);
1371 }
1372 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1373 install_public_key(pk, &pubkeys);
1374
1375 if (certificate->get_type(certificate) == CERT_X509)
1376 {
1377 x509_t *x509 = (x509_t*)certificate;
1378 enumerator_t *enumerator;
1379
1380 /* insert all subjectAltNames from X.509 certificates */
1381 enumerator = x509->create_subjectAltName_enumerator(x509);
1382 while (enumerator->enumerate(enumerator, &id))
1383 {
1384 if (id->get_type(id) != ID_ANY)
1385 {
1386 pk = malloc_thing(pubkey_t);
1387 zero(pk);
1388 pk->id = id->clone(id);
1389 pk->public_key = certificate->get_public_key(certificate);
1390 pk->dns_auth_level = dns_auth_level;
1391 pk->until_time = until;
1392 pk->issuer = issuer->clone(issuer);
1393 pk->serial = chunk_clone(serialNumber);
1394 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1395 install_public_key(pk, &pubkeys);
1396 }
1397 }
1398 enumerator->destroy(enumerator);
1399 }
1400 else
1401 {
1402 pgp_certificate_t *pgp_cert = (pgp_certificate_t*)certificate;
1403 chunk_t fingerprint = pgp_cert->get_fingerprint(pgp_cert);
1404
1405 /* add v3 or v4 PGP fingerprint */
1406 pk = malloc_thing(pubkey_t);
1407 zero(pk);
1408 pk->id = identification_create_from_encoding(ID_KEY_ID, fingerprint);
1409 pk->public_key = certificate->get_public_key(certificate);
1410 pk->dns_auth_level = dns_auth_level;
1411 pk->until_time = until;
1412 delete_public_keys(pk->id, pk_type, pk->issuer, pk->serial);
1413 install_public_key(pk, &pubkeys);
1414 }
1415 }
1416
1417 /* when a X.509 certificate gets revoked, all instances of
1418 * the corresponding public key must be removed
1419 */
1420 void remove_x509_public_key(const cert_t *cert)
1421 {
1422 public_key_t *revoked_key = cert->cert->get_public_key(cert->cert);
1423 pubkey_list_t *p, **pp;
1424
1425 p = pubkeys;
1426 pp = &pubkeys;
1427
1428 while(p != NULL)
1429 {
1430 if (revoked_key->equals(revoked_key, p->key->public_key))
1431 {
1432 /* remove p from list and free memory */
1433 *pp = free_public_keyentry(p);
1434 loglog(RC_LOG_SERIOUS, "invalid public key deleted");
1435 }
1436 else
1437 {
1438 pp = &p->next;
1439 }
1440 p =*pp;
1441 }
1442 revoked_key->destroy(revoked_key);
1443 }
1444
1445 /*
1446 * list all public keys in the chained list
1447 */
1448 void list_public_keys(bool utc)
1449 {
1450 pubkey_list_t *p = pubkeys;
1451
1452 if (p != NULL)
1453 {
1454 whack_log(RC_COMMENT, " ");
1455 whack_log(RC_COMMENT, "List of Public Keys:");
1456 }
1457
1458 while (p != NULL)
1459 {
1460 pubkey_t *key = p->key;
1461 public_key_t *public = key->public_key;
1462 chunk_t keyid;
1463
1464 whack_log(RC_COMMENT, " ");
1465 whack_log(RC_COMMENT, " identity: '%Y'", key->id);
1466 whack_log(RC_COMMENT, " pubkey: %N %4d bits, until %T %s",
1467 key_type_names, public->get_type(public),
1468 public->get_keysize(public),
1469 &key->until_time, utc,
1470 check_expiry(key->until_time, PUBKEY_WARNING_INTERVAL, TRUE));
1471 if (public->get_fingerprint(public, KEYID_PUBKEY_INFO_SHA1, &keyid))
1472 {
1473 whack_log(RC_COMMENT," keyid: %#B", &keyid);
1474 }
1475 if (key->issuer)
1476 {
1477 whack_log(RC_COMMENT," issuer: \"%Y\"", key->issuer);
1478 }
1479 if (key->serial.len)
1480 {
1481 whack_log(RC_COMMENT," serial: %#B", &key->serial);
1482 }
1483 p = p->next;
1484 }
1485 }