xref: /openbsd-src/sbin/isakmpd/ike_auth.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /* $OpenBSD: ike_auth.c,v 1.110 2007/04/16 13:01:39 moritz 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 			}
285 		}
286 
287 		if (fd < 0) {
288 			/* No key found, try default key. */
289 			keyfile = conf_get_str("X509-certificates",
290 			    "Private-key");
291 
292 			fd = monitor_open(keyfile, O_RDONLY, 0);
293 			if (fd < 0) {
294 				log_print("ike_auth_get_key: failed opening "
295 				    "\"%s\"", keyfile);
296 				return 0;
297 			}
298 		}
299 
300 		if (check_file_secrecy_fd(fd, keyfile, &fsize)) {
301 			free(privkeyfile);
302 			return 0;
303 		}
304 
305 		if ((keyfp = fdopen(fd, "r")) == NULL) {
306 			log_print("ike_auth_get_key: fdopen failed");
307 			free(privkeyfile);
308 			return 0;
309 		}
310 #if SSLEAY_VERSION_NUMBER >= 0x00904100L
311 		rsakey = PEM_read_RSAPrivateKey(keyfp, NULL, NULL, NULL);
312 #else
313 		rsakey = PEM_read_RSAPrivateKey(keyfp, NULL, NULL);
314 #endif
315 		fclose(keyfp);
316 
317 		free(privkeyfile);
318 
319 		if (!rsakey) {
320 			log_print("ike_auth_get_key: "
321 			    "PEM_read_bio_RSAPrivateKey failed");
322 			return 0;
323 		}
324 		return rsakey;
325 
326 	default:
327 		log_print("ike_auth_get_key: unknown key type %d", type);
328 		return 0;
329 	}
330 
331 	return key;
332 }
333 
334 static u_int8_t *
335 pre_shared_gen_skeyid(struct exchange *exchange, size_t *sz)
336 {
337 	struct prf     *prf;
338 	struct ipsec_exch *ie = exchange->data;
339 	u_int8_t       *skeyid, *buf = 0;
340 	unsigned char  *key;
341 	size_t          keylen;
342 
343 	/*
344 	 * If we're the responder and have the initiator's ID (which is the
345 	 * case in Aggressive mode), try to find the preshared key in the
346 	 * section of the initiator's Phase 1 ID.  This allows us to do
347 	 * mobile user support with preshared keys.
348          */
349 	if (!exchange->initiator && exchange->id_i) {
350 		switch (exchange->id_i[0]) {
351 		case IPSEC_ID_IPV4_ADDR:
352 		case IPSEC_ID_IPV6_ADDR:
353 			util_ntoa((char **) &buf,
354 			    exchange->id_i[0] == IPSEC_ID_IPV4_ADDR ? AF_INET :
355 			    AF_INET6, exchange->id_i + ISAKMP_ID_DATA_OFF -
356 			    ISAKMP_GEN_SZ);
357 			if (!buf)
358 				return 0;
359 			break;
360 
361 		case IPSEC_ID_FQDN:
362 		case IPSEC_ID_USER_FQDN:
363 			buf = calloc(exchange->id_i_len - ISAKMP_ID_DATA_OFF +
364 			    ISAKMP_GEN_SZ + 1, sizeof(char));
365 			if (!buf) {
366 				log_print("pre_shared_gen_skeyid: malloc (%lu"
367 				    ") failed",
368 				    (unsigned long)exchange->id_i_len -
369 				    ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
370 				return 0;
371 			}
372 			memcpy(buf,
373 			    exchange->id_i + ISAKMP_ID_DATA_OFF -
374 			    ISAKMP_GEN_SZ,
375 			    exchange->id_i_len - ISAKMP_ID_DATA_OFF +
376 			    ISAKMP_GEN_SZ);
377 			break;
378 
379 			/* XXX Support more ID types ? */
380 		default:
381 			break;
382 		}
383 	}
384 	/*
385 	 * Get the pre-shared key for our peer. This will work even if the key
386 	 * has been passed to us through a mechanism like PFKEYv2.
387          */
388 	key = ike_auth_get_key(IKE_AUTH_PRE_SHARED, exchange->name,
389 	    (char *)buf, &keylen);
390 	free(buf);
391 
392 	/* Fail if no key could be found.  */
393 	if (!key)
394 		return 0;
395 
396 	/* Store the secret key for later policy processing.  */
397 	exchange->recv_key = calloc(keylen + 1, sizeof(char));
398 	exchange->recv_keytype = ISAKMP_KEY_PASSPHRASE;
399 	if (!exchange->recv_key) {
400 		log_error("pre_shared_gen_skeyid: malloc (%lu) failed",
401 		    (unsigned long)keylen);
402 		free(key);
403 		return 0;
404 	}
405 	memcpy(exchange->recv_key, key, keylen);
406 	exchange->recv_certtype = ISAKMP_CERTENC_NONE;
407 	free(key);
408 
409 	prf = prf_alloc(ie->prf_type, ie->hash->type, exchange->recv_key,
410 	    keylen);
411 	if (!prf)
412 		return 0;
413 
414 	*sz = prf->blocksize;
415 	skeyid = malloc(*sz);
416 	if (!skeyid) {
417 		log_error("pre_shared_gen_skeyid: malloc (%lu) failed",
418 		    (unsigned long)*sz);
419 		prf_free(prf);
420 		return 0;
421 	}
422 	prf->Init(prf->prfctx);
423 	prf->Update(prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
424 	prf->Update(prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
425 	prf->Final(skeyid, prf->prfctx);
426 	prf_free(prf);
427 	return skeyid;
428 }
429 
430 /* Both DSS & RSA signature authentication use this algorithm.  */
431 static u_int8_t *
432 sig_gen_skeyid(struct exchange *exchange, size_t *sz)
433 {
434 	struct prf     *prf;
435 	struct ipsec_exch *ie = exchange->data;
436 	u_int8_t       *skeyid;
437 	unsigned char  *key;
438 
439 	key = malloc(exchange->nonce_i_len + exchange->nonce_r_len);
440 	if (!key)
441 		return 0;
442 	memcpy(key, exchange->nonce_i, exchange->nonce_i_len);
443 	memcpy(key + exchange->nonce_i_len, exchange->nonce_r,
444 	    exchange->nonce_r_len);
445 
446 	LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: PRF type %d, hash %d",
447 	    ie->prf_type, ie->hash->type));
448 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
449 	    "sig_gen_skeyid: SKEYID initialized with",
450 	    (u_int8_t *)key, exchange->nonce_i_len + exchange->nonce_r_len));
451 
452 	prf = prf_alloc(ie->prf_type, ie->hash->type, key,
453 	    exchange->nonce_i_len + exchange->nonce_r_len);
454 	free(key);
455 	if (!prf)
456 		return 0;
457 
458 	*sz = prf->blocksize;
459 	skeyid = malloc(*sz);
460 	if (!skeyid) {
461 		log_error("sig_gen_skeyid: malloc (%lu) failed",
462 		    (unsigned long)*sz);
463 		prf_free(prf);
464 		return 0;
465 	}
466 	LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: g^xy length %lu",
467 	    (unsigned long)ie->g_x_len));
468 	LOG_DBG_BUF((LOG_NEGOTIATION, 80,
469 	    "sig_gen_skeyid: SKEYID fed with g^xy", ie->g_xy, ie->g_x_len));
470 
471 	prf->Init(prf->prfctx);
472 	prf->Update(prf->prfctx, ie->g_xy, ie->g_x_len);
473 	prf->Final(skeyid, prf->prfctx);
474 	prf_free(prf);
475 	return skeyid;
476 }
477 
478 #ifdef notdef
479 /*
480  * Both standard and revised RSA encryption authentication use this SKEYID
481  * computation.
482  */
483 static u_int8_t *
484 enc_gen_skeyid(struct exchange *exchange, size_t *sz)
485 {
486 	struct prf     *prf;
487 	struct ipsec_exch *ie = exchange->data;
488 	struct hash    *hash = ie->hash;
489 	u_int8_t       *skeyid;
490 
491 	hash->Init(hash->ctx);
492 	hash->Update(hash->ctx, exchange->nonce_i, exchange->nonce_i_len);
493 	hash->Update(hash->ctx, exchange->nonce_r, exchange->nonce_r_len);
494 	hash->Final(hash->digest, hash->ctx);
495 	prf = prf_alloc(ie->prf_type, hash->type, hash->digest, *sz);
496 	if (!prf)
497 		return 0;
498 
499 	*sz = prf->blocksize;
500 	skeyid = malloc(*sz);
501 	if (!skeyid) {
502 		log_error("enc_gen_skeyid: malloc (%d) failed", *sz);
503 		prf_free(prf);
504 		return 0;
505 	}
506 	prf->Init(prf->prfctx);
507 	prf->Update(prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
508 	prf->Final(skeyid, prf->prfctx);
509 	prf_free(prf);
510 	return skeyid;
511 }
512 #endif				/* notdef */
513 
514 static int
515 pre_shared_decode_hash(struct message *msg)
516 {
517 	struct exchange *exchange = msg->exchange;
518 	struct ipsec_exch *ie = exchange->data;
519 	struct payload *payload;
520 	size_t          hashsize = ie->hash->hashsize;
521 	char            header[80];
522 	int             initiator = exchange->initiator;
523 	u_int8_t      **hash_p;
524 
525 	/* Choose the right fields to fill-in.  */
526 	hash_p = initiator ? &ie->hash_r : &ie->hash_i;
527 
528 	payload = payload_first(msg, ISAKMP_PAYLOAD_HASH);
529 	if (!payload) {
530 		log_print("pre_shared_decode_hash: no HASH payload found");
531 		return -1;
532 	}
533 	/* Check that the hash is of the correct size.  */
534 	if (GET_ISAKMP_GEN_LENGTH(payload->p) - ISAKMP_GEN_SZ != hashsize)
535 		return -1;
536 
537 	/* XXX Need this hash be in the SA?  */
538 	*hash_p = malloc(hashsize);
539 	if (!*hash_p) {
540 		log_error("pre_shared_decode_hash: malloc (%lu) failed",
541 		    (unsigned long)hashsize);
542 		return -1;
543 	}
544 	memcpy(*hash_p, payload->p + ISAKMP_HASH_DATA_OFF, hashsize);
545 	snprintf(header, sizeof header, "pre_shared_decode_hash: HASH_%c",
546 	    initiator ? 'R' : 'I');
547 	LOG_DBG_BUF((LOG_MISC, 80, header, *hash_p, hashsize));
548 
549 	payload->flags |= PL_MARK;
550 	return 0;
551 }
552 
553 /* Decrypt the HASH in SIG, we already need a parsed ID payload.  */
554 static int
555 rsa_sig_decode_hash(struct message *msg)
556 {
557 	struct cert_handler *handler;
558 	struct exchange *exchange = msg->exchange;
559 	struct ipsec_exch *ie = exchange->data;
560 	struct payload *p;
561 	void           *cert = 0;
562 	u_int8_t       *rawcert = 0, **hash_p, **id_cert, *id;
563 	u_int32_t       rawcertlen, *id_cert_len;
564 	RSA            *key = 0;
565 	size_t          hashsize = ie->hash->hashsize, id_len;
566 	char            header[80];
567 	int             len, initiator = exchange->initiator;
568 	int             found = 0, n, i, id_found;
569 #if defined (USE_DNSSEC)
570 	u_int8_t       *rawkey = 0;
571 	u_int32_t       rawkeylen;
572 #endif
573 
574 	/* Choose the right fields to fill-in.  */
575 	hash_p = initiator ? &ie->hash_r : &ie->hash_i;
576 	id = initiator ? exchange->id_r : exchange->id_i;
577 	id_len = initiator ? exchange->id_r_len : exchange->id_i_len;
578 
579 	if (!id || id_len == 0) {
580 		log_print("rsa_sig_decode_hash: ID is missing");
581 		return -1;
582 	}
583 	/*
584 	 * XXX Assume we should use the same kind of certification as the
585 	 * remote...  moreover, just use the first CERT payload to decide what
586 	 * to use.
587          */
588 	p = payload_first(msg, ISAKMP_PAYLOAD_CERT);
589 	if (!p)
590 		handler = cert_get(ISAKMP_CERTENC_KEYNOTE);
591 	else
592 		handler = cert_get(GET_ISAKMP_CERT_ENCODING(p->p));
593 	if (!handler) {
594 		log_print("rsa_sig_decode_hash: cert_get (%d) failed",
595 		    p ? GET_ISAKMP_CERT_ENCODING(p->p) : -1);
596 		return -1;
597 	}
598 	/*
599 	 * We need the policy session initialized now, so we can add
600 	 * credentials etc.
601          */
602 	exchange->policy_id = kn_init();
603 	if (exchange->policy_id == -1) {
604 		log_print("rsa_sig_decode_hash: failed to initialize policy "
605 		    "session");
606 		return -1;
607 	}
608 
609 	/* Obtain a certificate from our certificate storage.  */
610 	if (handler->cert_obtain(id, id_len, 0, &rawcert, &rawcertlen)) {
611 		if (handler->id == ISAKMP_CERTENC_X509_SIG) {
612 			cert = handler->cert_get(rawcert, rawcertlen);
613 			if (!cert)
614 				LOG_DBG((LOG_CRYPTO, 50, "rsa_sig_decode_hash:"
615 				    " certificate malformed"));
616 			else {
617 				if (!handler->cert_get_key(cert, &key)) {
618 					log_print("rsa_sig_decode_hash: "
619 					    "decoding certificate failed");
620 					handler->cert_free(cert);
621 				} else {
622 					found++;
623 					LOG_DBG((LOG_CRYPTO, 40,
624 					    "rsa_sig_decode_hash: using cert "
625 					    "of type %d", handler->id));
626 					exchange->recv_cert = cert;
627 					exchange->recv_certtype = handler->id;
628 					x509_generate_kn(exchange->policy_id,
629 					    cert);
630 				}
631 			}
632 		} else if (handler->id == ISAKMP_CERTENC_KEYNOTE)
633 			handler->cert_insert(exchange->policy_id, rawcert);
634 		free(rawcert);
635 	}
636 	/*
637 	 * Walk over potential CERT payloads in this message.
638 	 * XXX I believe this is the wrong spot for this.  CERTs can appear
639 	 * anytime.
640          */
641 	TAILQ_FOREACH(p, &msg->payload[ISAKMP_PAYLOAD_CERT], link) {
642 		p->flags |= PL_MARK;
643 
644 		/*
645 		 * When we have found a key, just walk over the rest, marking
646 		 * them.
647 		 */
648 		if (found)
649 			continue;
650 
651 		handler = cert_get(GET_ISAKMP_CERT_ENCODING(p->p));
652 		if (!handler) {
653 			LOG_DBG((LOG_MISC, 30, "rsa_sig_decode_hash: "
654 			    "no handler for %s CERT encoding",
655 			    constant_name(isakmp_certenc_cst,
656 			    GET_ISAKMP_CERT_ENCODING(p->p))));
657 			continue;
658 		}
659 		cert = handler->cert_get(p->p + ISAKMP_CERT_DATA_OFF,
660 		    GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_CERT_DATA_OFF);
661 		if (!cert) {
662 			log_print("rsa_sig_decode_hash: "
663 			    "can not get data from CERT");
664 			continue;
665 		}
666 		if (!handler->cert_validate(cert)) {
667 			handler->cert_free(cert);
668 			log_print("rsa_sig_decode_hash: received CERT can't "
669 			    "be validated");
670 			continue;
671 		}
672 		if (GET_ISAKMP_CERT_ENCODING(p->p) ==
673 		    ISAKMP_CERTENC_X509_SIG) {
674 			if (!handler->cert_get_subjects(cert, &n, &id_cert,
675 			    &id_cert_len)) {
676 				handler->cert_free(cert);
677 				log_print("rsa_sig_decode_hash: can not get "
678 				    "subject from CERT");
679 				continue;
680 			}
681 			id_found = 0;
682 			for (i = 0; i < n; i++)
683 				if (id_cert_len[i] == id_len &&
684 				    id[0] == id_cert[i][0] &&
685 				    memcmp(id + 4, id_cert[i] + 4, id_len - 4)
686 				    == 0) {
687 					id_found++;
688 					break;
689 				}
690 			if (!id_found) {
691 				handler->cert_free(cert);
692 				log_print("rsa_sig_decode_hash: no CERT "
693 				    "subject match the ID");
694 				free(id_cert);
695 				continue;
696 			}
697 			cert_free_subjects(n, id_cert, id_cert_len);
698 		}
699 		if (!handler->cert_get_key(cert, &key)) {
700 			handler->cert_free(cert);
701 			log_print("rsa_sig_decode_hash: decoding payload CERT "
702 			    "failed");
703 			continue;
704 		}
705 		/* We validated the cert, cache it for later use.  */
706 		handler->cert_insert(exchange->policy_id, cert);
707 
708 		exchange->recv_cert = cert;
709 		exchange->recv_certtype = GET_ISAKMP_CERT_ENCODING(p->p);
710 
711 		if (exchange->recv_certtype == ISAKMP_CERTENC_KEYNOTE) {
712 			struct keynote_deckey dc;
713 			char           *pp;
714 
715 			dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
716 			dc.dec_key = key;
717 
718 			pp = kn_encode_key(&dc, INTERNAL_ENC_PKCS1,
719 			    ENCODING_HEX, KEYNOTE_PUBLIC_KEY);
720 			if (pp == NULL) {
721 				kn_free_key(&dc);
722 				log_print("rsa_sig_decode_hash: failed to "
723 				    "ASCII-encode key");
724 				return -1;
725 			}
726 			if (asprintf(&exchange->keynote_key, "rsa-hex:%s",
727 			    pp) == -1) {
728 				free(pp);
729 				kn_free_key(&dc);
730 				log_print("rsa_sig_decode_hash: failed to asprintf()");
731 				return -1;
732 			}
733 			free(pp);
734 		}
735 		found++;
736 	}
737 
738 #if defined (USE_DNSSEC)
739 	/*
740 	 * If no certificate provided a key, try to find a validated DNSSEC
741 	 * KEY.
742 	 */
743 	if (!found) {
744 		rawkey = dns_get_key(IKE_AUTH_RSA_SIG, msg, &rawkeylen);
745 
746 		/* We need to convert 'void *rawkey' into 'RSA *key'.  */
747 		if (dns_RSA_dns_to_x509(rawkey, rawkeylen, &key) == 0)
748 			found++;
749 		else
750 			log_print("rsa_sig_decode_hash: KEY to RSA key "
751 			    "conversion failed");
752 
753 		free(rawkey);
754 	}
755 #endif				/* USE_DNSSEC */
756 
757 	/* If we still have not found a key, try to read it from a file. */
758 	if (!found)
759 		if (get_raw_key_from_file(IKE_AUTH_RSA_SIG, id, id_len, &key)
760 		    != -1)
761 			found++;
762 
763 	if (!found) {
764 		log_print("rsa_sig_decode_hash: no public key found");
765 		return -1;
766 	}
767 	p = payload_first(msg, ISAKMP_PAYLOAD_SIG);
768 	if (!p) {
769 		log_print("rsa_sig_decode_hash: missing signature payload");
770 		RSA_free(key);
771 		return -1;
772 	}
773 	/* Check that the sig is of the correct size.  */
774 	len = GET_ISAKMP_GEN_LENGTH(p->p) - ISAKMP_SIG_SZ;
775 	if (len != RSA_size(key)) {
776 		RSA_free(key);
777 		log_print("rsa_sig_decode_hash: "
778 		    "SIG payload length does not match public key");
779 		return -1;
780 	}
781 	*hash_p = malloc(len);
782 	if (!*hash_p) {
783 		RSA_free(key);
784 		log_error("rsa_sig_decode_hash: malloc (%d) failed", len);
785 		return -1;
786 	}
787 	len = RSA_public_decrypt(len, p->p + ISAKMP_SIG_DATA_OFF, *hash_p, key,
788 	    RSA_PKCS1_PADDING);
789 	if (len == -1) {
790 		RSA_free(key);
791 		log_print("rsa_sig_decode_hash: RSA_public_decrypt () failed");
792 		return -1;
793 	}
794 	/* Store key for later use */
795 	exchange->recv_key = key;
796 	exchange->recv_keytype = ISAKMP_KEY_RSA;
797 
798 	if (len != (int)hashsize) {
799 		free(*hash_p);
800 		*hash_p = 0;
801 		log_print("rsa_sig_decode_hash: len %lu != hashsize %lu",
802 		    (unsigned long)len, (unsigned long)hashsize);
803 		return -1;
804 	}
805 	snprintf(header, sizeof header, "rsa_sig_decode_hash: HASH_%c",
806 	    initiator ? 'R' : 'I');
807 	LOG_DBG_BUF((LOG_MISC, 80, header, *hash_p, hashsize));
808 
809 	p->flags |= PL_MARK;
810 	return 0;
811 }
812 
813 static int
814 pre_shared_encode_hash(struct message *msg)
815 {
816 	struct exchange *exchange = msg->exchange;
817 	struct ipsec_exch *ie = exchange->data;
818 	size_t          hashsize = ie->hash->hashsize;
819 	char            header[80];
820 	int             initiator = exchange->initiator;
821 	u_int8_t       *buf;
822 
823 	buf = ipsec_add_hash_payload(msg, hashsize);
824 	if (!buf)
825 		return -1;
826 
827 	if (ike_auth_hash(exchange, buf + ISAKMP_HASH_DATA_OFF) == -1)
828 		return -1;
829 
830 	snprintf(header, sizeof header, "pre_shared_encode_hash: HASH_%c",
831 	    initiator ? 'I' : 'R');
832 	LOG_DBG_BUF((LOG_MISC, 80, header, buf + ISAKMP_HASH_DATA_OFF,
833 	    hashsize));
834 	return 0;
835 }
836 
837 /* Encrypt the HASH into a SIG type.  */
838 static int
839 rsa_sig_encode_hash(struct message *msg)
840 {
841 	struct exchange *exchange = msg->exchange;
842 	struct ipsec_exch *ie = exchange->data;
843 	size_t          hashsize = ie->hash->hashsize, id_len;
844 	struct cert_handler *handler;
845 	char            header[80];
846 	int             initiator = exchange->initiator, idtype;
847 	u_int8_t       *buf, *data, *buf2, *id;
848 	u_int32_t       datalen;
849 	int32_t         sigsize;
850 	void           *sent_key;
851 
852 	id = initiator ? exchange->id_i : exchange->id_r;
853 	id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
854 
855 	/* We may have been provided these by the kernel */
856 	buf = (u_int8_t *)conf_get_str(exchange->name, "Credentials");
857 	if (buf && (idtype = conf_get_num(exchange->name, "Credential_Type",
858 	    -1)) != -1) {
859 		exchange->sent_certtype = idtype;
860 		handler = cert_get(idtype);
861 		if (!handler) {
862 			log_print("rsa_sig_encode_hash: cert_get (%d) failed",
863 			    idtype);
864 			return -1;
865 		}
866 		exchange->sent_cert =
867 		    handler->cert_from_printable((char *)buf);
868 		if (!exchange->sent_cert) {
869 			log_print("rsa_sig_encode_hash: failed to retrieve "
870 			    "certificate");
871 			return -1;
872 		}
873 		handler->cert_serialize(exchange->sent_cert, &data, &datalen);
874 		if (!data) {
875 			log_print("rsa_sig_encode_hash: cert serialization "
876 			    "failed");
877 			return -1;
878 		}
879 		goto aftercert;	/* Skip all the certificate discovery */
880 	}
881 	/* XXX This needs to be configurable.  */
882 	idtype = ISAKMP_CERTENC_KEYNOTE;
883 
884 	/* Find a certificate with subjectAltName = id.  */
885 	handler = cert_get(idtype);
886 	if (!handler) {
887 		idtype = ISAKMP_CERTENC_X509_SIG;
888 		handler = cert_get(idtype);
889 		if (!handler) {
890 			log_print("rsa_sig_encode_hash: cert_get(%d) failed",
891 			    idtype);
892 			return -1;
893 		}
894 	}
895 	if (handler->cert_obtain(id, id_len, 0, &data, &datalen) == 0) {
896 		if (idtype == ISAKMP_CERTENC_KEYNOTE) {
897 			idtype = ISAKMP_CERTENC_X509_SIG;
898 			handler = cert_get(idtype);
899 			if (!handler) {
900 				log_print("rsa_sig_encode_hash: cert_get(%d) "
901 				    "failed", idtype);
902 				return -1;
903 			}
904 			if (handler->cert_obtain(id, id_len, 0, &data,
905 			    &datalen) == 0) {
906 				LOG_DBG((LOG_MISC, 10, "rsa_sig_encode_hash: "
907 				    "no certificate to send for id %s",
908 				    ipsec_id_string(id, id_len)));
909 				goto skipcert;
910 			}
911 		} else {
912 			LOG_DBG((LOG_MISC, 10,
913 			    "rsa_sig_encode_hash: no certificate to send"
914 			    " for id %s", ipsec_id_string(id, id_len)));
915 			goto skipcert;
916 		}
917 	}
918 	/* Let's store the certificate we are going to use */
919 	exchange->sent_certtype = idtype;
920 	exchange->sent_cert = handler->cert_get(data, datalen);
921 	if (!exchange->sent_cert) {
922 		free(data);
923 		log_print("rsa_sig_encode_hash: failed to get certificate "
924 		    "from wire encoding");
925 		return -1;
926 	}
927 aftercert:
928 
929 	buf = realloc(data, ISAKMP_CERT_SZ + datalen);
930 	if (!buf) {
931 		log_error("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
932 		    ISAKMP_CERT_SZ + datalen);
933 		free(data);
934 		return -1;
935 	}
936 	memmove(buf + ISAKMP_CERT_SZ, buf, datalen);
937 	SET_ISAKMP_CERT_ENCODING(buf, idtype);
938 	if (message_add_payload(msg, ISAKMP_PAYLOAD_CERT, buf,
939 	    ISAKMP_CERT_SZ + datalen, 1)) {
940 		free(buf);
941 		return -1;
942 	}
943 skipcert:
944 
945 	/* Again, we may have these from the kernel */
946 	buf = (u_int8_t *)conf_get_str(exchange->name, "PKAuthentication");
947 	if (buf) {
948 		key_from_printable(ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE,
949 		    (char *)buf, &data, &datalen);
950 		if (!data) {
951 			log_print("rsa_sig_encode_hash: badly formatted RSA "
952 			    "private key");
953 			return 0;
954 		}
955 		sent_key = key_internalize(ISAKMP_KEY_RSA,
956 		    ISAKMP_KEYTYPE_PRIVATE, data, datalen);
957 		if (!sent_key) {
958 			log_print("rsa_sig_encode_hash: bad RSA private key "
959 			    "from dynamic SA acquisition subsystem");
960 			return 0;
961 		}
962 	} else {
963 		/* Try through the regular means.  */
964 		switch (id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ]) {
965 		case IPSEC_ID_IPV4_ADDR:
966 		case IPSEC_ID_IPV6_ADDR:
967 			util_ntoa((char **)&buf2,
968 			    id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ] ==
969 			    IPSEC_ID_IPV4_ADDR ? AF_INET : AF_INET6,
970 			    id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
971 			if (!buf2)
972 				return 0;
973 			break;
974 
975 		case IPSEC_ID_FQDN:
976 		case IPSEC_ID_USER_FQDN:
977 			buf2 = calloc(id_len - ISAKMP_ID_DATA_OFF +
978 			    ISAKMP_GEN_SZ + 1, sizeof(char));
979 			if (!buf2) {
980 				log_print("rsa_sig_encode_hash: malloc (%lu) "
981 				    "failed", (unsigned long)id_len -
982 				    ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
983 				return 0;
984 			}
985 			memcpy(buf2, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
986 			    id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
987 			break;
988 
989 			/* XXX Support more ID types?  */
990 		default:
991 			buf2 = 0;
992 			return 0;
993 		}
994 
995 		sent_key = ike_auth_get_key(IKE_AUTH_RSA_SIG, exchange->name,
996 		    (char *)buf2, 0);
997 		free(buf2);
998 
999 		/* Did we find a key?  */
1000 		if (!sent_key) {
1001 			log_print("rsa_sig_encode_hash: "
1002 			    "could not get private key");
1003 			return -1;
1004 		}
1005 	}
1006 
1007 	/* Enable RSA blinding.  */
1008 	if (RSA_blinding_on(sent_key, NULL) != 1) {
1009 		log_error("rsa_sig_encode_hash: RSA_blinding_on () failed.");
1010 		RSA_free(sent_key);
1011 		return -1;
1012 	}
1013 	/* XXX hashsize is not necessarily prf->blocksize.  */
1014 	buf = malloc(hashsize);
1015 	if (!buf) {
1016 		log_error("rsa_sig_encode_hash: malloc (%lu) failed",
1017 		    (unsigned long)hashsize);
1018 		RSA_free(sent_key);
1019 		return -1;
1020 	}
1021 	if (ike_auth_hash(exchange, buf) == -1) {
1022 		free(buf);
1023 		RSA_free(sent_key);
1024 		return -1;
1025 	}
1026 	snprintf(header, sizeof header, "rsa_sig_encode_hash: HASH_%c",
1027 	    initiator ? 'I' : 'R');
1028 	LOG_DBG_BUF((LOG_MISC, 80, header, buf, hashsize));
1029 
1030 	data = malloc(RSA_size(sent_key));
1031 	if (!data) {
1032 		log_error("rsa_sig_encode_hash: malloc (%d) failed",
1033 		    RSA_size(sent_key));
1034 		free(buf);
1035 		RSA_free(sent_key);
1036 		return -1;
1037 	}
1038 	sigsize = RSA_private_encrypt(hashsize, buf, data, sent_key,
1039 	    RSA_PKCS1_PADDING);
1040 	if (sigsize == -1) {
1041 		log_print("rsa_sig_encode_hash: "
1042 		    "RSA_private_encrypt () failed");
1043 		free(data);
1044 		free(buf);
1045 		RSA_free(sent_key);
1046 		return -1;
1047 	}
1048 	datalen = (u_int32_t) sigsize;
1049 
1050 	free(buf);
1051 	RSA_free(sent_key);
1052 
1053 	buf = realloc(data, ISAKMP_SIG_SZ + datalen);
1054 	if (!buf) {
1055 		log_error("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1056 		    ISAKMP_SIG_SZ + datalen);
1057 		free(data);
1058 		return -1;
1059 	}
1060 	memmove(buf + ISAKMP_SIG_SZ, buf, datalen);
1061 
1062 	snprintf(header, sizeof header, "rsa_sig_encode_hash: SIG_%c",
1063 	    initiator ? 'I' : 'R');
1064 	LOG_DBG_BUF((LOG_MISC, 80, header, buf + ISAKMP_SIG_DATA_OFF,
1065 	    datalen));
1066 	if (message_add_payload(msg, ISAKMP_PAYLOAD_SIG, buf,
1067 	    ISAKMP_SIG_SZ + datalen, 1)) {
1068 		free(buf);
1069 		return -1;
1070 	}
1071 	return 0;
1072 }
1073 
1074 int
1075 ike_auth_hash(struct exchange *exchange, u_int8_t *buf)
1076 {
1077 	struct ipsec_exch *ie = exchange->data;
1078 	struct prf     *prf;
1079 	struct hash    *hash = ie->hash;
1080 	int             initiator = exchange->initiator;
1081 	u_int8_t       *id;
1082 	size_t          id_len;
1083 
1084 	/* Choose the right fields to fill-in.  */
1085 	id = initiator ? exchange->id_i : exchange->id_r;
1086 	id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
1087 
1088 	/* Allocate the prf and start calculating our HASH.  */
1089 	prf = prf_alloc(ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1090 	if (!prf)
1091 		return -1;
1092 
1093 	prf->Init(prf->prfctx);
1094 	prf->Update(prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1095 	prf->Update(prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1096 	prf->Update(prf->prfctx, exchange->cookies +
1097 	    (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1098 	    ISAKMP_HDR_ICOOKIE_LEN);
1099 	prf->Update(prf->prfctx, exchange->cookies +
1100 	    (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1101 	    ISAKMP_HDR_ICOOKIE_LEN);
1102 	prf->Update(prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1103 	prf->Update(prf->prfctx, id, id_len);
1104 	prf->Final(buf, prf->prfctx);
1105 	prf_free(prf);
1106 	return 0;
1107 }
1108 
1109 static int
1110 get_raw_key_from_file(int type, u_int8_t *id, size_t id_len, RSA **rsa)
1111 {
1112 	char            filename[FILENAME_MAX];
1113 	char           *fstr;
1114 	FILE           *keyfp;
1115 
1116 	if (type != IKE_AUTH_RSA_SIG) {	/* XXX More types? */
1117 		LOG_DBG((LOG_NEGOTIATION, 20, "get_raw_key_from_file: "
1118 		    "invalid auth type %d\n", type));
1119 		return -1;
1120 	}
1121 	*rsa = 0;
1122 
1123 	fstr = conf_get_str("General", "Pubkey-directory");
1124 	if (!fstr)
1125 		fstr = CONF_DFLT_PUBKEY_DIR;
1126 
1127 	if (snprintf(filename, sizeof filename, "%s/", fstr) >
1128 	    (int)sizeof filename - 1)
1129 		return -1;
1130 
1131 	fstr = ipsec_id_string(id, id_len);
1132 	if (!fstr) {
1133 		LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1134 		    "ipsec_id_string failed"));
1135 		return -1;
1136 	}
1137 	strlcat(filename, fstr, sizeof filename - strlen(filename));
1138 	free(fstr);
1139 
1140 	/* If the file does not exist, fail silently.  */
1141 	keyfp = monitor_fopen(filename, "r");
1142 	if (keyfp) {
1143 		*rsa = PEM_read_RSA_PUBKEY(keyfp, NULL, NULL, NULL);
1144 		if (!*rsa) {
1145 			rewind(keyfp);
1146 			*rsa = PEM_read_RSAPublicKey(keyfp, NULL, NULL, NULL);
1147 		}
1148 		if (!*rsa)
1149 			log_print("get_raw_key_from_file: failed to get "
1150 			    "public key %s", filename);
1151 		fclose(keyfp);
1152 	} else if (errno != ENOENT) {
1153 		log_error("get_raw_key_from_file: monitor_fopen "
1154 		    "(\"%s\", \"r\") failed", filename);
1155 		return -1;
1156 	} else
1157 		LOG_DBG((LOG_NEGOTIATION, 50,
1158 		    "get_raw_key_from_file: file %s not found", filename));
1159 
1160 	return (*rsa ? 0 : -1);
1161 }
1162