xref: /openbsd/sbin/isakmpd/ike_auth.c (revision a6445c1d)
1 /* $OpenBSD: ike_auth.c,v 1.112 2014/08/25 08:00:48 doug Exp $	 */
2 /* $EOM: ike_auth.c,v 1.59 2000/11/21 00:21:31 angelos Exp $	 */
3 
4 /*
5  * Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist.  All rights reserved.
6  * Copyright (c) 1999 Niels Provos.  All rights reserved.
7  * Copyright (c) 1999 Angelos D. Keromytis.  All rights reserved.
8  * Copyright (c) 2000, 2001, 2003 H�kan Olsson.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /*
32  * This code was written under funding by Ericsson Radio Systems.
33  */
34 
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <regex.h>
46 #include <keynote.h>
47 #include <policy.h>
48 
49 #include "cert.h"
50 #include "conf.h"
51 #include "constants.h"
52 #if defined (USE_DNSSEC)
53 #include "dnssec.h"
54 #endif
55 #include "exchange.h"
56 #include "hash.h"
57 #include "ike_auth.h"
58 #include "ipsec.h"
59 #include "ipsec_doi.h"
60 #include "libcrypto.h"
61 #include "log.h"
62 #include "message.h"
63 #include "monitor.h"
64 #include "prf.h"
65 #include "transport.h"
66 #include "util.h"
67 #include "key.h"
68 #include "x509.h"
69 
70 #ifdef notyet
71 static u_int8_t *enc_gen_skeyid(struct exchange *, size_t *);
72 #endif
73 static u_int8_t *pre_shared_gen_skeyid(struct exchange *, size_t *);
74 
75 static int      pre_shared_decode_hash(struct message *);
76 static int      pre_shared_encode_hash(struct message *);
77 
78 static u_int8_t *sig_gen_skeyid(struct exchange *, size_t *);
79 static int      rsa_sig_decode_hash(struct message *);
80 static int      rsa_sig_encode_hash(struct message *);
81 
82 static int      get_raw_key_from_file(int, u_int8_t *, size_t, RSA **);
83 
84 static int      ike_auth_hash(struct exchange *, u_int8_t *);
85 
86 static struct ike_auth ike_auth[] = {
87 	{
88 		IKE_AUTH_PRE_SHARED, pre_shared_gen_skeyid,
89 		pre_shared_decode_hash,
90 		pre_shared_encode_hash
91 	},
92 #ifdef notdef
93 	{
94 		IKE_AUTH_DSS, sig_gen_skeyid,
95 		pre_shared_decode_hash,
96 		pre_shared_encode_hash
97 	},
98 #endif
99 	{
100 		IKE_AUTH_RSA_SIG, sig_gen_skeyid,
101 		rsa_sig_decode_hash,
102 		rsa_sig_encode_hash
103 	},
104 #ifdef notdef
105 	{
106 		IKE_AUTH_RSA_ENC, enc_gen_skeyid,
107 		pre_shared_decode_hash,
108 		pre_shared_encode_hash
109 	},
110 	{
111 		IKE_AUTH_RSA_ENC_REV, enc_gen_skeyid,
112 		pre_shared_decode_hash,
113 		pre_shared_encode_hash
114 	},
115 #endif
116 };
117 
118 struct ike_auth *
119 ike_auth_get(u_int16_t id)
120 {
121 	size_t	i;
122 
123 	for (i = 0; i < sizeof ike_auth / sizeof ike_auth[0]; i++)
124 		if (id == ike_auth[i].id)
125 			return &ike_auth[i];
126 	return 0;
127 }
128 
129 /*
130  * Find and decode the configured key (pre-shared or public) for the
131  * peer denoted by ID.  Stash the len in KEYLEN.
132  */
133 static void *
134 ike_auth_get_key(int type, char *id, char *local_id, size_t *keylen)
135 {
136 	char	*key, *buf;
137 	char	*keyfile, *privkeyfile;
138 	FILE	*keyfp;
139 	RSA	*rsakey;
140 	size_t	 fsize, pkflen;
141 	int	 fd;
142 
143 	switch (type) {
144 	case IKE_AUTH_PRE_SHARED:
145 		/* Get the pre-shared key for our peer.  */
146 		key = conf_get_str(id, "Authentication");
147 		if (!key && local_id)
148 			key = conf_get_str(local_id, "Authentication");
149 
150 		if (!key) {
151 			log_print("ike_auth_get_key: "
152 			    "no key found for peer \"%s\" or local ID \"%s\"",
153 			    id, local_id ? local_id : "<none>");
154 			return 0;
155 		}
156 		/* If the key starts with 0x it is in hex format.  */
157 		if (strncasecmp(key, "0x", 2) == 0) {
158 			*keylen = (strlen(key) - 1) / 2;
159 			buf = malloc(*keylen);
160 			if (!buf) {
161 				log_error("ike_auth_get_key: malloc (%lu) "
162 				    "failed", (unsigned long)*keylen);
163 				return 0;
164 			}
165 			if (hex2raw(key + 2, (unsigned char *)buf, *keylen)) {
166 				free(buf);
167 				log_print("ike_auth_get_key: invalid hex key "
168 				    "%s", key);
169 				return 0;
170 			}
171 			key = buf;
172 		} else {
173 			buf = key;
174 			key = strdup(buf);
175 			if (!key) {
176 				log_error("ike_auth_get_key: strdup() failed");
177 				return 0;
178 			}
179 			*keylen = strlen(key);
180 		}
181 		break;
182 
183 	case IKE_AUTH_RSA_SIG:
184 		if (local_id && (keyfile = conf_get_str("KeyNote",
185 		    "Credential-directory")) != 0) {
186 			struct stat     sb;
187 			struct keynote_deckey dc;
188 			char           *privkeyfile, *buf2;
189 			size_t          size;
190 
191 			if (asprintf(&privkeyfile, "%s/%s/%s", keyfile,
192 			    local_id, PRIVATE_KEY_FILE) == -1) {
193 				log_print("ike_auth_get_key: failed to asprintf()");
194 				return 0;
195 			}
196 			keyfile = privkeyfile;
197 
198 			fd = monitor_open(keyfile, O_RDONLY, 0);
199 			if (fd < 0) {
200 				free(keyfile);
201 				goto ignorekeynote;
202 			}
203 			size = (size_t)sb.st_size;
204 
205 			if (fstat(fd, &sb) < 0) {
206 				log_print("ike_auth_get_key: fstat failed");
207 				free(keyfile);
208 				close(fd);
209 				return 0;
210 			}
211 			size = (size_t)sb.st_size;
212 
213 			buf = calloc(size + 1, sizeof(char));
214 			if (!buf) {
215 				log_print("ike_auth_get_key: failed allocating"
216 				    " %lu bytes", (unsigned long)size + 1);
217 				free(keyfile);
218 				close(fd);
219 				return 0;
220 			}
221 			if (read(fd, buf, size) != (ssize_t)size) {
222 				free(buf);
223 				log_print("ike_auth_get_key: "
224 				    "failed reading %lu bytes from \"%s\"",
225 				    (unsigned long)size, keyfile);
226 				free(keyfile);
227 				close(fd);
228 				return 0;
229 			}
230 			close(fd);
231 
232 			/* Parse private key string */
233 			buf2 = kn_get_string(buf);
234 			free(buf);
235 
236 			if (!buf2 || kn_decode_key(&dc, buf2,
237 			    KEYNOTE_PRIVATE_KEY) == -1) {
238 				free(buf2);
239 				log_print("ike_auth_get_key: failed decoding "
240 				    "key in \"%s\"", keyfile);
241 				free(keyfile);
242 				return 0;
243 			}
244 			free(buf2);
245 
246 			if (dc.dec_algorithm != KEYNOTE_ALGORITHM_RSA) {
247 				log_print("ike_auth_get_key: wrong algorithm "
248 				    "type %d in \"%s\"", dc.dec_algorithm,
249 				    keyfile);
250 				free(keyfile);
251 				kn_free_key(&dc);
252 				return 0;
253 			}
254 			free(keyfile);
255 			return dc.dec_key;
256 		}
257 ignorekeynote:
258 		/* Otherwise, try X.509 */
259 
260 		privkeyfile = keyfile = NULL;
261 		fd = -1;
262 
263 		if (local_id) {
264 			/* Look in Private-key-directory. */
265 			keyfile = conf_get_str("X509-certificates",
266 			    "Private-key-directory");
267 			pkflen = strlen(keyfile) + strlen(local_id) + sizeof "/";
268 			privkeyfile = calloc(pkflen, sizeof(char));
269 			if (!privkeyfile) {
270 				log_print("ike_auth_get_key: failed to "
271 				    "allocate %lu bytes", (unsigned long)pkflen);
272 				return 0;
273 			}
274 
275 			snprintf(privkeyfile, pkflen, "%s/%s", keyfile,
276 			    local_id);
277 			keyfile = privkeyfile;
278 
279 			fd = monitor_open(keyfile, O_RDONLY, 0);
280 			if (fd < 0 && errno != ENOENT) {
281 				log_print("ike_auth_get_key: failed opening "
282 				    "\"%s\"", keyfile);
283 				free(privkeyfile);
284 				privkeyfile = NULL;
285 				keyfile = NULL;
286 			}
287 		}
288 
289 		if (fd < 0) {
290 			/* No key found, try default key. */
291 			keyfile = conf_get_str("X509-certificates",
292 			    "Private-key");
293 
294 			fd = monitor_open(keyfile, O_RDONLY, 0);
295 			if (fd < 0) {
296 				log_print("ike_auth_get_key: failed opening "
297 				    "\"%s\"", keyfile);
298 				return 0;
299 			}
300 		}
301 
302 		if (check_file_secrecy_fd(fd, keyfile, &fsize)) {
303 			free(privkeyfile);
304 			close(fd);
305 			return 0;
306 		}
307 
308 		if ((keyfp = fdopen(fd, "r")) == NULL) {
309 			log_print("ike_auth_get_key: fdopen failed");
310 			free(privkeyfile);
311 			close(fd);
312 			return 0;
313 		}
314 #if SSLEAY_VERSION_NUMBER >= 0x00904100L
315 		rsakey = PEM_read_RSAPrivateKey(keyfp, NULL, NULL, NULL);
316 #else
317 		rsakey = PEM_read_RSAPrivateKey(keyfp, NULL, NULL);
318 #endif
319 		fclose(keyfp);
320 
321 		free(privkeyfile);
322 
323 		if (!rsakey) {
324 			log_print("ike_auth_get_key: "
325 			    "PEM_read_bio_RSAPrivateKey failed");
326 			return 0;
327 		}
328 		return rsakey;
329 
330 	default:
331 		log_print("ike_auth_get_key: unknown key type %d", type);
332 		return 0;
333 	}
334 
335 	return key;
336 }
337 
338 static u_int8_t *
339 pre_shared_gen_skeyid(struct exchange *exchange, size_t *sz)
340 {
341 	struct prf     *prf;
342 	struct ipsec_exch *ie = exchange->data;
343 	u_int8_t       *skeyid, *buf = 0;
344 	unsigned char  *key;
345 	size_t          keylen;
346 
347 	/*
348 	 * If we're the responder and have the initiator's ID (which is the
349 	 * case in Aggressive mode), try to find the preshared key in the
350 	 * section of the initiator's Phase 1 ID.  This allows us to do
351 	 * mobile user support with preshared keys.
352          */
353 	if (!exchange->initiator && exchange->id_i) {
354 		switch (exchange->id_i[0]) {
355 		case IPSEC_ID_IPV4_ADDR:
356 		case IPSEC_ID_IPV6_ADDR:
357 			util_ntoa((char **) &buf,
358 			    exchange->id_i[0] == IPSEC_ID_IPV4_ADDR ? AF_INET :
359 			    AF_INET6, exchange->id_i + ISAKMP_ID_DATA_OFF -
360 			    ISAKMP_GEN_SZ);
361 			if (!buf)
362 				return 0;
363 			break;
364 
365 		case IPSEC_ID_FQDN:
366 		case IPSEC_ID_USER_FQDN:
367 			buf = calloc(exchange->id_i_len - ISAKMP_ID_DATA_OFF +
368 			    ISAKMP_GEN_SZ + 1, sizeof(char));
369 			if (!buf) {
370 				log_print("pre_shared_gen_skeyid: malloc (%lu"
371 				    ") failed",
372 				    (unsigned long)exchange->id_i_len -
373 				    ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
374 				return 0;
375 			}
376 			memcpy(buf,
377 			    exchange->id_i + ISAKMP_ID_DATA_OFF -
378 			    ISAKMP_GEN_SZ,
379 			    exchange->id_i_len - ISAKMP_ID_DATA_OFF +
380 			    ISAKMP_GEN_SZ);
381 			break;
382 
383 			/* XXX Support more ID types ? */
384 		default:
385 			break;
386 		}
387 	}
388 	/*
389 	 * Get the pre-shared key for our peer. This will work even if the key
390 	 * has been passed to us through a mechanism like PFKEYv2.
391          */
392 	key = ike_auth_get_key(IKE_AUTH_PRE_SHARED, exchange->name,
393 	    (char *)buf, &keylen);
394 	free(buf);
395 
396 	/* Fail if no key could be found.  */
397 	if (!key)
398 		return 0;
399 
400 	/* Store the secret key for later policy processing.  */
401 	exchange->recv_key = calloc(keylen + 1, sizeof(char));
402 	exchange->recv_keytype = ISAKMP_KEY_PASSPHRASE;
403 	if (!exchange->recv_key) {
404 		log_error("pre_shared_gen_skeyid: malloc (%lu) failed",
405 		    (unsigned long)keylen);
406 		free(key);
407 		return 0;
408 	}
409 	memcpy(exchange->recv_key, key, keylen);
410 	exchange->recv_certtype = ISAKMP_CERTENC_NONE;
411 	free(key);
412 
413 	prf = prf_alloc(ie->prf_type, ie->hash->type, exchange->recv_key,
414 	    keylen);
415 	if (!prf)
416 		return 0;
417 
418 	*sz = prf->blocksize;
419 	skeyid = malloc(*sz);
420 	if (!skeyid) {
421 		log_error("pre_shared_gen_skeyid: malloc (%lu) failed",
422 		    (unsigned long)*sz);
423 		prf_free(prf);
424 		return 0;
425 	}
426 	prf->Init(prf->prfctx);
427 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
428 	prf->Update(prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
429 	prf->Final(skeyid, prf->prfctx);
430 	prf_free(prf);
431 	return skeyid;
432 }
433 
434 /* Both DSS & RSA signature authentication use this algorithm.  */
435 static u_int8_t *
436 sig_gen_skeyid(struct exchange *exchange, size_t *sz)
437 {
438 	struct prf     *prf;
439 	struct ipsec_exch *ie = exchange->data;
440 	u_int8_t       *skeyid;
441 	unsigned char  *key;
442 
443 	key = malloc(exchange->nonce_i_len + exchange->nonce_r_len);
444 	if (!key)
445 		return 0;
446 	memcpy(key, exchange->nonce_i, exchange->nonce_i_len);
447 	memcpy(key + exchange->nonce_i_len, exchange->nonce_r,
448 	    exchange->nonce_r_len);
449 
450 	LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: PRF type %d, hash %d",
451 	    ie->prf_type, ie->hash->type));
452 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
453 	    "sig_gen_skeyid: SKEYID initialized with",
454 	    (u_int8_t *)key, exchange->nonce_i_len + exchange->nonce_r_len));
455 
456 	prf = prf_alloc(ie->prf_type, ie->hash->type, key,
457 	    exchange->nonce_i_len + exchange->nonce_r_len);
458 	free(key);
459 	if (!prf)
460 		return 0;
461 
462 	*sz = prf->blocksize;
463 	skeyid = malloc(*sz);
464 	if (!skeyid) {
465 		log_error("sig_gen_skeyid: malloc (%lu) failed",
466 		    (unsigned long)*sz);
467 		prf_free(prf);
468 		return 0;
469 	}
470 	LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: g^xy length %lu",
471 	    (unsigned long)ie->g_x_len));
472 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
473 	    "sig_gen_skeyid: SKEYID fed with g^xy", ie->g_xy, ie->g_x_len));
474 
475 	prf->Init(prf->prfctx);
476 	prf->Update(prf->prfctx, ie->g_xy, ie->g_x_len);
477 	prf->Final(skeyid, prf->prfctx);
478 	prf_free(prf);
479 	return skeyid;
480 }
481 
482 #ifdef notdef
483 /*
484  * Both standard and revised RSA encryption authentication use this SKEYID
485  * computation.
486  */
487 static u_int8_t *
488 enc_gen_skeyid(struct exchange *exchange, size_t *sz)
489 {
490 	struct prf     *prf;
491 	struct ipsec_exch *ie = exchange->data;
492 	struct hash    *hash = ie->hash;
493 	u_int8_t       *skeyid;
494 
495 	hash->Init(hash->ctx);
496 	hash->Update(hash->ctx, exchange->nonce_i, exchange->nonce_i_len);
497 	hash->Update(hash->ctx, exchange->nonce_r, exchange->nonce_r_len);
498 	hash->Final(hash->digest, hash->ctx);
499 	prf = prf_alloc(ie->prf_type, hash->type, hash->digest, *sz);
500 	if (!prf)
501 		return 0;
502 
503 	*sz = prf->blocksize;
504 	skeyid = malloc(*sz);
505 	if (!skeyid) {
506 		log_error("enc_gen_skeyid: malloc (%d) failed", *sz);
507 		prf_free(prf);
508 		return 0;
509 	}
510 	prf->Init(prf->prfctx);
511 	prf->Update(prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
512 	prf->Final(skeyid, prf->prfctx);
513 	prf_free(prf);
514 	return skeyid;
515 }
516 #endif				/* notdef */
517 
518 static int
519 pre_shared_decode_hash(struct message *msg)
520 {
521 	struct exchange *exchange = msg->exchange;
522 	struct ipsec_exch *ie = exchange->data;
523 	struct payload *payload;
524 	size_t          hashsize = ie->hash->hashsize;
525 	char            header[80];
526 	int             initiator = exchange->initiator;
527 	u_int8_t      **hash_p;
528 
529 	/* Choose the right fields to fill-in.  */
530 	hash_p = initiator ? &ie->hash_r : &ie->hash_i;
531 
532 	payload = payload_first(msg, ISAKMP_PAYLOAD_HASH);
533 	if (!payload) {
534 		log_print("pre_shared_decode_hash: no HASH payload found");
535 		return -1;
536 	}
537 	/* Check that the hash is of the correct size.  */
538 	if (GET_ISAKMP_GEN_LENGTH(payload->p) - ISAKMP_GEN_SZ != hashsize)
539 		return -1;
540 
541 	/* XXX Need this hash be in the SA?  */
542 	*hash_p = malloc(hashsize);
543 	if (!*hash_p) {
544 		log_error("pre_shared_decode_hash: malloc (%lu) failed",
545 		    (unsigned long)hashsize);
546 		return -1;
547 	}
548 	memcpy(*hash_p, payload->p + ISAKMP_HASH_DATA_OFF, hashsize);
549 	snprintf(header, sizeof header, "pre_shared_decode_hash: HASH_%c",
550 	    initiator ? 'R' : 'I');
551 	LOG_DBG_BUF((LOG_MISC, 80, header, *hash_p, hashsize));
552 
553 	payload->flags |= PL_MARK;
554 	return 0;
555 }
556 
557 /* Decrypt the HASH in SIG, we already need a parsed ID payload.  */
558 static int
559 rsa_sig_decode_hash(struct message *msg)
560 {
561 	struct cert_handler *handler;
562 	struct exchange *exchange = msg->exchange;
563 	struct ipsec_exch *ie = exchange->data;
564 	struct payload *p;
565 	void           *cert = 0;
566 	u_int8_t       *rawcert = 0, **hash_p, **id_cert, *id;
567 	u_int32_t       rawcertlen, *id_cert_len;
568 	RSA            *key = 0;
569 	size_t          hashsize = ie->hash->hashsize, id_len;
570 	char            header[80];
571 	int             len, initiator = exchange->initiator;
572 	int             found = 0, n, i, id_found;
573 #if defined (USE_DNSSEC)
574 	u_int8_t       *rawkey = 0;
575 	u_int32_t       rawkeylen;
576 #endif
577 
578 	/* Choose the right fields to fill-in.  */
579 	hash_p = initiator ? &ie->hash_r : &ie->hash_i;
580 	id = initiator ? exchange->id_r : exchange->id_i;
581 	id_len = initiator ? exchange->id_r_len : exchange->id_i_len;
582 
583 	if (!id || id_len == 0) {
584 		log_print("rsa_sig_decode_hash: ID is missing");
585 		return -1;
586 	}
587 	/*
588 	 * XXX Assume we should use the same kind of certification as the
589 	 * remote...  moreover, just use the first CERT payload to decide what
590 	 * to use.
591          */
592 	p = payload_first(msg, ISAKMP_PAYLOAD_CERT);
593 	if (!p)
594 		handler = cert_get(ISAKMP_CERTENC_KEYNOTE);
595 	else
596 		handler = cert_get(GET_ISAKMP_CERT_ENCODING(p->p));
597 	if (!handler) {
598 		log_print("rsa_sig_decode_hash: cert_get (%d) failed",
599 		    p ? GET_ISAKMP_CERT_ENCODING(p->p) : -1);
600 		return -1;
601 	}
602 	/*
603 	 * We need the policy session initialized now, so we can add
604 	 * credentials etc.
605          */
606 	exchange->policy_id = kn_init();
607 	if (exchange->policy_id == -1) {
608 		log_print("rsa_sig_decode_hash: failed to initialize policy "
609 		    "session");
610 		return -1;
611 	}
612 
613 	/* Obtain a certificate from our certificate storage.  */
614 	if (handler->cert_obtain(id, id_len, 0, &rawcert, &rawcertlen)) {
615 		if (handler->id == ISAKMP_CERTENC_X509_SIG) {
616 			cert = handler->cert_get(rawcert, rawcertlen);
617 			if (!cert)
618 				LOG_DBG((LOG_CRYPTO, 50, "rsa_sig_decode_hash:"
619 				    " certificate malformed"));
620 			else {
621 				if (!handler->cert_get_key(cert, &key)) {
622 					log_print("rsa_sig_decode_hash: "
623 					    "decoding certificate failed");
624 					handler->cert_free(cert);
625 				} else {
626 					found++;
627 					LOG_DBG((LOG_CRYPTO, 40,
628 					    "rsa_sig_decode_hash: using cert "
629 					    "of type %d", handler->id));
630 					exchange->recv_cert = cert;
631 					exchange->recv_certtype = handler->id;
632 					x509_generate_kn(exchange->policy_id,
633 					    cert);
634 				}
635 			}
636 		} else if (handler->id == ISAKMP_CERTENC_KEYNOTE)
637 			handler->cert_insert(exchange->policy_id, rawcert);
638 		free(rawcert);
639 	}
640 	/*
641 	 * Walk over potential CERT payloads in this message.
642 	 * XXX I believe this is the wrong spot for this.  CERTs can appear
643 	 * anytime.
644          */
645 	TAILQ_FOREACH(p, &msg->payload[ISAKMP_PAYLOAD_CERT], link) {
646 		p->flags |= PL_MARK;
647 
648 		/*
649 		 * When we have found a key, just walk over the rest, marking
650 		 * them.
651 		 */
652 		if (found)
653 			continue;
654 
655 		handler = cert_get(GET_ISAKMP_CERT_ENCODING(p->p));
656 		if (!handler) {
657 			LOG_DBG((LOG_MISC, 30, "rsa_sig_decode_hash: "
658 			    "no handler for %s CERT encoding",
659 			    constant_name(isakmp_certenc_cst,
660 			    GET_ISAKMP_CERT_ENCODING(p->p))));
661 			continue;
662 		}
663 		cert = handler->cert_get(p->p + ISAKMP_CERT_DATA_OFF,
664 		    GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_CERT_DATA_OFF);
665 		if (!cert) {
666 			log_print("rsa_sig_decode_hash: "
667 			    "can not get data from CERT");
668 			continue;
669 		}
670 		if (!handler->cert_validate(cert)) {
671 			handler->cert_free(cert);
672 			log_print("rsa_sig_decode_hash: received CERT can't "
673 			    "be validated");
674 			continue;
675 		}
676 		if (GET_ISAKMP_CERT_ENCODING(p->p) ==
677 		    ISAKMP_CERTENC_X509_SIG) {
678 			if (!handler->cert_get_subjects(cert, &n, &id_cert,
679 			    &id_cert_len)) {
680 				handler->cert_free(cert);
681 				log_print("rsa_sig_decode_hash: can not get "
682 				    "subject from CERT");
683 				continue;
684 			}
685 			id_found = 0;
686 			for (i = 0; i < n; i++)
687 				if (id_cert_len[i] == id_len &&
688 				    id[0] == id_cert[i][0] &&
689 				    memcmp(id + 4, id_cert[i] + 4, id_len - 4)
690 				    == 0) {
691 					id_found++;
692 					break;
693 				}
694 			if (!id_found) {
695 				handler->cert_free(cert);
696 				log_print("rsa_sig_decode_hash: no CERT "
697 				    "subject match the ID");
698 				free(id_cert);
699 				continue;
700 			}
701 			cert_free_subjects(n, id_cert, id_cert_len);
702 		}
703 		if (!handler->cert_get_key(cert, &key)) {
704 			handler->cert_free(cert);
705 			log_print("rsa_sig_decode_hash: decoding payload CERT "
706 			    "failed");
707 			continue;
708 		}
709 		/* We validated the cert, cache it for later use.  */
710 		handler->cert_insert(exchange->policy_id, cert);
711 
712 		exchange->recv_cert = cert;
713 		exchange->recv_certtype = GET_ISAKMP_CERT_ENCODING(p->p);
714 
715 		if (exchange->recv_certtype == ISAKMP_CERTENC_KEYNOTE) {
716 			struct keynote_deckey dc;
717 			char           *pp;
718 
719 			dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
720 			dc.dec_key = key;
721 
722 			pp = kn_encode_key(&dc, INTERNAL_ENC_PKCS1,
723 			    ENCODING_HEX, KEYNOTE_PUBLIC_KEY);
724 			if (pp == NULL) {
725 				kn_free_key(&dc);
726 				log_print("rsa_sig_decode_hash: failed to "
727 				    "ASCII-encode key");
728 				return -1;
729 			}
730 			if (asprintf(&exchange->keynote_key, "rsa-hex:%s",
731 			    pp) == -1) {
732 				free(pp);
733 				kn_free_key(&dc);
734 				log_print("rsa_sig_decode_hash: failed to asprintf()");
735 				return -1;
736 			}
737 			free(pp);
738 		}
739 		found++;
740 	}
741 
742 #if defined (USE_DNSSEC)
743 	/*
744 	 * If no certificate provided a key, try to find a validated DNSSEC
745 	 * KEY.
746 	 */
747 	if (!found) {
748 		rawkey = dns_get_key(IKE_AUTH_RSA_SIG, msg, &rawkeylen);
749 
750 		/* We need to convert 'void *rawkey' into 'RSA *key'.  */
751 		if (dns_RSA_dns_to_x509(rawkey, rawkeylen, &key) == 0)
752 			found++;
753 		else
754 			log_print("rsa_sig_decode_hash: KEY to RSA key "
755 			    "conversion failed");
756 
757 		free(rawkey);
758 	}
759 #endif				/* USE_DNSSEC */
760 
761 	/* If we still have not found a key, try to read it from a file. */
762 	if (!found)
763 		if (get_raw_key_from_file(IKE_AUTH_RSA_SIG, id, id_len, &key)
764 		    != -1)
765 			found++;
766 
767 	if (!found) {
768 		log_print("rsa_sig_decode_hash: no public key found");
769 		return -1;
770 	}
771 	p = payload_first(msg, ISAKMP_PAYLOAD_SIG);
772 	if (!p) {
773 		log_print("rsa_sig_decode_hash: missing signature payload");
774 		RSA_free(key);
775 		return -1;
776 	}
777 	/* Check that the sig is of the correct size.  */
778 	len = GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_SIG_SZ;
779 	if (len != RSA_size(key)) {
780 		RSA_free(key);
781 		log_print("rsa_sig_decode_hash: "
782 		    "SIG payload length does not match public key");
783 		return -1;
784 	}
785 	*hash_p = malloc(len);
786 	if (!*hash_p) {
787 		RSA_free(key);
788 		log_error("rsa_sig_decode_hash: malloc (%d) failed", len);
789 		return -1;
790 	}
791 	len = RSA_public_decrypt(len, p->p + ISAKMP_SIG_DATA_OFF, *hash_p, key,
792 	    RSA_PKCS1_PADDING);
793 	if (len == -1) {
794 		RSA_free(key);
795 		log_print("rsa_sig_decode_hash: RSA_public_decrypt () failed");
796 		return -1;
797 	}
798 	/* Store key for later use */
799 	exchange->recv_key = key;
800 	exchange->recv_keytype = ISAKMP_KEY_RSA;
801 
802 	if (len != (int)hashsize) {
803 		free(*hash_p);
804 		*hash_p = 0;
805 		log_print("rsa_sig_decode_hash: len %lu != hashsize %lu",
806 		    (unsigned long)len, (unsigned long)hashsize);
807 		return -1;
808 	}
809 	snprintf(header, sizeof header, "rsa_sig_decode_hash: HASH_%c",
810 	    initiator ? 'R' : 'I');
811 	LOG_DBG_BUF((LOG_MISC, 80, header, *hash_p, hashsize));
812 
813 	p->flags |= PL_MARK;
814 	return 0;
815 }
816 
817 static int
818 pre_shared_encode_hash(struct message *msg)
819 {
820 	struct exchange *exchange = msg->exchange;
821 	struct ipsec_exch *ie = exchange->data;
822 	size_t          hashsize = ie->hash->hashsize;
823 	char            header[80];
824 	int             initiator = exchange->initiator;
825 	u_int8_t       *buf;
826 
827 	buf = ipsec_add_hash_payload(msg, hashsize);
828 	if (!buf)
829 		return -1;
830 
831 	if (ike_auth_hash(exchange, buf + ISAKMP_HASH_DATA_OFF) == -1)
832 		return -1;
833 
834 	snprintf(header, sizeof header, "pre_shared_encode_hash: HASH_%c",
835 	    initiator ? 'I' : 'R');
836 	LOG_DBG_BUF((LOG_MISC, 80, header, buf + ISAKMP_HASH_DATA_OFF,
837 	    hashsize));
838 	return 0;
839 }
840 
841 /* Encrypt the HASH into a SIG type.  */
842 static int
843 rsa_sig_encode_hash(struct message *msg)
844 {
845 	struct exchange *exchange = msg->exchange;
846 	struct ipsec_exch *ie = exchange->data;
847 	size_t          hashsize = ie->hash->hashsize, id_len;
848 	struct cert_handler *handler;
849 	char            header[80];
850 	int             initiator = exchange->initiator, idtype;
851 	u_int8_t       *buf, *data, *buf2, *id;
852 	u_int32_t       datalen;
853 	int32_t         sigsize;
854 	void           *sent_key;
855 
856 	id = initiator ? exchange->id_i : exchange->id_r;
857 	id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
858 
859 	/* We may have been provided these by the kernel */
860 	buf = (u_int8_t *)conf_get_str(exchange->name, "Credentials");
861 	if (buf && (idtype = conf_get_num(exchange->name, "Credential_Type",
862 	    -1)) != -1) {
863 		exchange->sent_certtype = idtype;
864 		handler = cert_get(idtype);
865 		if (!handler) {
866 			log_print("rsa_sig_encode_hash: cert_get (%d) failed",
867 			    idtype);
868 			return -1;
869 		}
870 		exchange->sent_cert =
871 		    handler->cert_from_printable((char *)buf);
872 		if (!exchange->sent_cert) {
873 			log_print("rsa_sig_encode_hash: failed to retrieve "
874 			    "certificate");
875 			return -1;
876 		}
877 		handler->cert_serialize(exchange->sent_cert, &data, &datalen);
878 		if (!data) {
879 			log_print("rsa_sig_encode_hash: cert serialization "
880 			    "failed");
881 			return -1;
882 		}
883 		goto aftercert;	/* Skip all the certificate discovery */
884 	}
885 	/* XXX This needs to be configurable.  */
886 	idtype = ISAKMP_CERTENC_KEYNOTE;
887 
888 	/* Find a certificate with subjectAltName = id.  */
889 	handler = cert_get(idtype);
890 	if (!handler) {
891 		idtype = ISAKMP_CERTENC_X509_SIG;
892 		handler = cert_get(idtype);
893 		if (!handler) {
894 			log_print("rsa_sig_encode_hash: cert_get(%d) failed",
895 			    idtype);
896 			return -1;
897 		}
898 	}
899 	if (handler->cert_obtain(id, id_len, 0, &data, &datalen) == 0) {
900 		if (idtype == ISAKMP_CERTENC_KEYNOTE) {
901 			idtype = ISAKMP_CERTENC_X509_SIG;
902 			handler = cert_get(idtype);
903 			if (!handler) {
904 				log_print("rsa_sig_encode_hash: cert_get(%d) "
905 				    "failed", idtype);
906 				return -1;
907 			}
908 			if (handler->cert_obtain(id, id_len, 0, &data,
909 			    &datalen) == 0) {
910 				LOG_DBG((LOG_MISC, 10, "rsa_sig_encode_hash: "
911 				    "no certificate to send for id %s",
912 				    ipsec_id_string(id, id_len)));
913 				goto skipcert;
914 			}
915 		} else {
916 			LOG_DBG((LOG_MISC, 10,
917 			    "rsa_sig_encode_hash: no certificate to send"
918 			    " for id %s", ipsec_id_string(id, id_len)));
919 			goto skipcert;
920 		}
921 	}
922 	/* Let's store the certificate we are going to use */
923 	exchange->sent_certtype = idtype;
924 	exchange->sent_cert = handler->cert_get(data, datalen);
925 	if (!exchange->sent_cert) {
926 		free(data);
927 		log_print("rsa_sig_encode_hash: failed to get certificate "
928 		    "from wire encoding");
929 		return -1;
930 	}
931 aftercert:
932 
933 	buf = realloc(data, ISAKMP_CERT_SZ + datalen);
934 	if (!buf) {
935 		log_error("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
936 		    ISAKMP_CERT_SZ + datalen);
937 		free(data);
938 		return -1;
939 	}
940 	memmove(buf + ISAKMP_CERT_SZ, buf, datalen);
941 	SET_ISAKMP_CERT_ENCODING(buf, idtype);
942 	if (message_add_payload(msg, ISAKMP_PAYLOAD_CERT, buf,
943 	    ISAKMP_CERT_SZ + datalen, 1)) {
944 		free(buf);
945 		return -1;
946 	}
947 skipcert:
948 
949 	/* Again, we may have these from the kernel */
950 	buf = (u_int8_t *)conf_get_str(exchange->name, "PKAuthentication");
951 	if (buf) {
952 		key_from_printable(ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE,
953 		    (char *)buf, &data, &datalen);
954 		if (!data) {
955 			log_print("rsa_sig_encode_hash: badly formatted RSA "
956 			    "private key");
957 			return 0;
958 		}
959 		sent_key = key_internalize(ISAKMP_KEY_RSA,
960 		    ISAKMP_KEYTYPE_PRIVATE, data, datalen);
961 		if (!sent_key) {
962 			log_print("rsa_sig_encode_hash: bad RSA private key "
963 			    "from dynamic SA acquisition subsystem");
964 			return 0;
965 		}
966 	} else {
967 		/* Try through the regular means.  */
968 		switch (id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ]) {
969 		case IPSEC_ID_IPV4_ADDR:
970 		case IPSEC_ID_IPV6_ADDR:
971 			util_ntoa((char **)&buf2,
972 			    id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ] ==
973 			    IPSEC_ID_IPV4_ADDR ? AF_INET : AF_INET6,
974 			    id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
975 			if (!buf2)
976 				return 0;
977 			break;
978 
979 		case IPSEC_ID_FQDN:
980 		case IPSEC_ID_USER_FQDN:
981 			buf2 = calloc(id_len - ISAKMP_ID_DATA_OFF +
982 			    ISAKMP_GEN_SZ + 1, sizeof(char));
983 			if (!buf2) {
984 				log_print("rsa_sig_encode_hash: malloc (%lu) "
985 				    "failed", (unsigned long)id_len -
986 				    ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
987 				return 0;
988 			}
989 			memcpy(buf2, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
990 			    id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
991 			break;
992 
993 			/* XXX Support more ID types?  */
994 		default:
995 			buf2 = 0;
996 			return 0;
997 		}
998 
999 		sent_key = ike_auth_get_key(IKE_AUTH_RSA_SIG, exchange->name,
1000 		    (char *)buf2, 0);
1001 		free(buf2);
1002 
1003 		/* Did we find a key?  */
1004 		if (!sent_key) {
1005 			log_print("rsa_sig_encode_hash: "
1006 			    "could not get private key");
1007 			return -1;
1008 		}
1009 	}
1010 
1011 	/* Enable RSA blinding.  */
1012 	if (RSA_blinding_on(sent_key, NULL) != 1) {
1013 		log_error("rsa_sig_encode_hash: RSA_blinding_on () failed.");
1014 		RSA_free(sent_key);
1015 		return -1;
1016 	}
1017 	/* XXX hashsize is not necessarily prf->blocksize.  */
1018 	buf = malloc(hashsize);
1019 	if (!buf) {
1020 		log_error("rsa_sig_encode_hash: malloc (%lu) failed",
1021 		    (unsigned long)hashsize);
1022 		RSA_free(sent_key);
1023 		return -1;
1024 	}
1025 	if (ike_auth_hash(exchange, buf) == -1) {
1026 		free(buf);
1027 		RSA_free(sent_key);
1028 		return -1;
1029 	}
1030 	snprintf(header, sizeof header, "rsa_sig_encode_hash: HASH_%c",
1031 	    initiator ? 'I' : 'R');
1032 	LOG_DBG_BUF((LOG_MISC, 80, header, buf, hashsize));
1033 
1034 	data = malloc(RSA_size(sent_key));
1035 	if (!data) {
1036 		log_error("rsa_sig_encode_hash: malloc (%d) failed",
1037 		    RSA_size(sent_key));
1038 		free(buf);
1039 		RSA_free(sent_key);
1040 		return -1;
1041 	}
1042 	sigsize = RSA_private_encrypt(hashsize, buf, data, sent_key,
1043 	    RSA_PKCS1_PADDING);
1044 	if (sigsize == -1) {
1045 		log_print("rsa_sig_encode_hash: "
1046 		    "RSA_private_encrypt () failed");
1047 		free(data);
1048 		free(buf);
1049 		RSA_free(sent_key);
1050 		return -1;
1051 	}
1052 	datalen = (u_int32_t) sigsize;
1053 
1054 	free(buf);
1055 	RSA_free(sent_key);
1056 
1057 	buf = realloc(data, ISAKMP_SIG_SZ + datalen);
1058 	if (!buf) {
1059 		log_error("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1060 		    ISAKMP_SIG_SZ + datalen);
1061 		free(data);
1062 		return -1;
1063 	}
1064 	memmove(buf + ISAKMP_SIG_SZ, buf, datalen);
1065 
1066 	snprintf(header, sizeof header, "rsa_sig_encode_hash: SIG_%c",
1067 	    initiator ? 'I' : 'R');
1068 	LOG_DBG_BUF((LOG_MISC, 80, header, buf + ISAKMP_SIG_DATA_OFF,
1069 	    datalen));
1070 	if (message_add_payload(msg, ISAKMP_PAYLOAD_SIG, buf,
1071 	    ISAKMP_SIG_SZ + datalen, 1)) {
1072 		free(buf);
1073 		return -1;
1074 	}
1075 	return 0;
1076 }
1077 
1078 int
1079 ike_auth_hash(struct exchange *exchange, u_int8_t *buf)
1080 {
1081 	struct ipsec_exch *ie = exchange->data;
1082 	struct prf     *prf;
1083 	struct hash    *hash = ie->hash;
1084 	int             initiator = exchange->initiator;
1085 	u_int8_t       *id;
1086 	size_t          id_len;
1087 
1088 	/* Choose the right fields to fill-in.  */
1089 	id = initiator ? exchange->id_i : exchange->id_r;
1090 	id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
1091 
1092 	/* Allocate the prf and start calculating our HASH.  */
1093 	prf = prf_alloc(ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1094 	if (!prf)
1095 		return -1;
1096 
1097 	prf->Init(prf->prfctx);
1098 	prf->Update(prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1099 	prf->Update(prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1100 	prf->Update(prf->prfctx, exchange->cookies +
1101 	    (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1102 	    ISAKMP_HDR_ICOOKIE_LEN);
1103 	prf->Update(prf->prfctx, exchange->cookies +
1104 	    (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1105 	    ISAKMP_HDR_ICOOKIE_LEN);
1106 	prf->Update(prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1107 	prf->Update(prf->prfctx, id, id_len);
1108 	prf->Final(buf, prf->prfctx);
1109 	prf_free(prf);
1110 	return 0;
1111 }
1112 
1113 static int
1114 get_raw_key_from_file(int type, u_int8_t *id, size_t id_len, RSA **rsa)
1115 {
1116 	char            filename[FILENAME_MAX];
1117 	char           *fstr;
1118 	FILE           *keyfp;
1119 
1120 	if (type != IKE_AUTH_RSA_SIG) {	/* XXX More types? */
1121 		LOG_DBG((LOG_NEGOTIATION, 20, "get_raw_key_from_file: "
1122 		    "invalid auth type %d\n", type));
1123 		return -1;
1124 	}
1125 	*rsa = 0;
1126 
1127 	fstr = conf_get_str("General", "Pubkey-directory");
1128 	if (!fstr)
1129 		fstr = CONF_DFLT_PUBKEY_DIR;
1130 
1131 	if (snprintf(filename, sizeof filename, "%s/", fstr) >
1132 	    (int)sizeof filename - 1)
1133 		return -1;
1134 
1135 	fstr = ipsec_id_string(id, id_len);
1136 	if (!fstr) {
1137 		LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1138 		    "ipsec_id_string failed"));
1139 		return -1;
1140 	}
1141 	strlcat(filename, fstr, sizeof filename - strlen(filename));
1142 	free(fstr);
1143 
1144 	/* If the file does not exist, fail silently.  */
1145 	keyfp = monitor_fopen(filename, "r");
1146 	if (keyfp) {
1147 		*rsa = PEM_read_RSA_PUBKEY(keyfp, NULL, NULL, NULL);
1148 		if (!*rsa) {
1149 			rewind(keyfp);
1150 			*rsa = PEM_read_RSAPublicKey(keyfp, NULL, NULL, NULL);
1151 		}
1152 		if (!*rsa)
1153 			log_print("get_raw_key_from_file: failed to get "
1154 			    "public key %s", filename);
1155 		fclose(keyfp);
1156 	} else if (errno != ENOENT) {
1157 		log_error("get_raw_key_from_file: monitor_fopen "
1158 		    "(\"%s\", \"r\") failed", filename);
1159 		return -1;
1160 	} else
1161 		LOG_DBG((LOG_NEGOTIATION, 50,
1162 		    "get_raw_key_from_file: file %s not found", filename));
1163 
1164 	return (*rsa ? 0 : -1);
1165 }
1166