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