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