xref: /openbsd-src/sbin/isakmpd/ike_auth.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: ike_auth.c,v 1.78 2003/06/10 16:41:29 deraadt 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, exchange->nonce_i_len + exchange->nonce_r_len));
450 
451   prf = prf_alloc (ie->prf_type, ie->hash->type, key,
452 		   exchange->nonce_i_len + exchange->nonce_r_len);
453   free (key);
454   if (!prf)
455     return 0;
456 
457   *sz = prf->blocksize;
458   skeyid = malloc (*sz);
459   if (!skeyid)
460     {
461       log_error ("sig_gen_skeyid: malloc (%lu) failed",
462 	(unsigned long)*sz);
463       prf_free (prf);
464       return 0;
465     }
466 
467   LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: g^xy length %lu",
468       (unsigned long)ie->g_x_len));
469   LOG_DBG_BUF((LOG_NEGOTIATION, 80,
470       "sig_gen_skeyid: SKEYID fed with g^xy", ie->g_xy, ie->g_x_len));
471 
472   prf->Init (prf->prfctx);
473   prf->Update (prf->prfctx, ie->g_xy, ie->g_x_len);
474   prf->Final (skeyid, prf->prfctx);
475   prf_free (prf);
476 
477   return skeyid;
478 }
479 #endif /* USE_X509 || USE_KEYNOTE */
480 
481 #ifdef notdef
482 /*
483  * Both standard and revised RSA encryption authentication use this SKEYID
484  * computation.
485  */
486 static u_int8_t *
487 enc_gen_skeyid (struct exchange *exchange, size_t *sz)
488 {
489   struct prf *prf;
490   struct ipsec_exch *ie = exchange->data;
491   struct hash *hash = ie->hash;
492   u_int8_t *skeyid;
493 
494   hash->Init (hash->ctx);
495   hash->Update (hash->ctx, exchange->nonce_i, exchange->nonce_i_len);
496   hash->Update (hash->ctx, exchange->nonce_r, exchange->nonce_r_len);
497   hash->Final (hash->digest, hash->ctx);
498   prf = prf_alloc (ie->prf_type, hash->type, hash->digest, *sz);
499   if (!prf)
500     return 0;
501 
502   *sz = prf->blocksize;
503   skeyid = malloc (*sz);
504   if (!skeyid)
505     {
506       log_error ("enc_gen_skeyid: malloc (%d) failed", *sz);
507       prf_free (prf);
508       return 0;
509     }
510 
511   prf->Init (prf->prfctx);
512   prf->Update (prf->prfctx, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
513   prf->Final (skeyid, prf->prfctx);
514   prf_free (prf);
515 
516   return skeyid;
517 }
518 #endif /* notdef */
519 
520 static int
521 pre_shared_decode_hash (struct message *msg)
522 {
523   struct exchange *exchange = msg->exchange;
524   struct ipsec_exch *ie = exchange->data;
525   struct payload *payload;
526   size_t hashsize = ie->hash->hashsize;
527   char header[80];
528   int initiator = exchange->initiator;
529   u_int8_t **hash_p;
530 
531   /* Choose the right fields to fill-in.  */
532   hash_p = initiator ? &ie->hash_r : &ie->hash_i;
533 
534   payload = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_HASH]);
535   if (!payload)
536     {
537       log_print ("pre_shared_decode_hash: no HASH payload found");
538       return -1;
539     }
540 
541   /* Check that the hash is of the correct size.  */
542   if (GET_ISAKMP_GEN_LENGTH (payload->p) - ISAKMP_GEN_SZ != hashsize)
543     return -1;
544 
545   /* XXX Need this hash be in the SA?  */
546   *hash_p = malloc (hashsize);
547   if (!*hash_p)
548     {
549       log_error ("pre_shared_decode_hash: malloc (%lu) failed",
550 	(unsigned long)hashsize);
551       return -1;
552     }
553 
554   memcpy (*hash_p, payload->p + ISAKMP_HASH_DATA_OFF, hashsize);
555   snprintf (header, sizeof header, "pre_shared_decode_hash: HASH_%c",
556 	    initiator ? 'R' : 'I');
557   LOG_DBG_BUF ((LOG_MISC, 80, header, *hash_p, hashsize));
558 
559   payload->flags |= PL_MARK;
560 
561   return 0;
562 }
563 
564 #if defined (USE_X509) || defined (USE_KEYNOTE)
565 /* Decrypt the HASH in SIG, we already need a parsed ID payload.  */
566 static int
567 rsa_sig_decode_hash (struct message *msg)
568 {
569   struct cert_handler *handler;
570   struct exchange *exchange = msg->exchange;
571   struct ipsec_exch *ie = exchange->data;
572   struct payload *p;
573   void *cert = 0;
574   u_int8_t *rawcert = 0;
575   u_int32_t rawcertlen;
576   RSA *key = 0;
577   size_t hashsize = ie->hash->hashsize;
578   char header[80];
579   int len;
580   int initiator = exchange->initiator;
581   u_int8_t **hash_p, **id_cert, *id;
582   u_int32_t *id_cert_len;
583   size_t id_len;
584   int found = 0, n, i, id_found;
585 #if defined (USE_DNSSEC)
586   u_int8_t *rawkey = 0;
587   u_int32_t rawkeylen;
588 #endif
589 
590   /* Choose the right fields to fill-in.  */
591   hash_p = initiator ? &ie->hash_r : &ie->hash_i;
592   id = initiator ? exchange->id_r : exchange->id_i;
593   id_len = initiator ? exchange->id_r_len : exchange->id_i_len;
594 
595   if (!id || id_len == 0)
596     {
597       log_print ("rsa_sig_decode_hash: ID is missing");
598       return -1;
599     }
600 
601   /*
602    * XXX Assume we should use the same kind of certification as the remote...
603    * moreover, just use the first CERT payload to decide what to use.
604    */
605   p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_CERT]);
606   if (!p)
607     handler = cert_get (ISAKMP_CERTENC_KEYNOTE);
608   else
609     handler = cert_get (GET_ISAKMP_CERT_ENCODING (p->p));
610   if (!handler)
611     {
612       log_print ("rsa_sig_decode_hash: cert_get (%d) failed",
613 		 p ? GET_ISAKMP_CERT_ENCODING (p->p) : -1);
614       return -1;
615     }
616 
617 #if defined (USE_POLICY) || defined (USE_KEYNOTE)
618   /*
619    * We need the policy session initialized now, so we can add
620    * credentials etc.
621    */
622   exchange->policy_id = kn_init ();
623   if (exchange->policy_id == -1)
624     {
625       log_print ("rsa_sig_decode_hash: failed to initialize policy session");
626       return -1;
627     }
628 #endif /* USE_POLICY || USE_KEYNOTE */
629 
630   /* Obtain a certificate from our certificate storage.  */
631   if (handler->cert_obtain (id, id_len, 0, &rawcert, &rawcertlen))
632     {
633       if (handler->id == ISAKMP_CERTENC_X509_SIG)
634         {
635 	  cert = handler->cert_get (rawcert, rawcertlen);
636 	  if (!cert)
637 	    LOG_DBG ((LOG_CRYPTO, 50,
638 		      "rsa_sig_decode_hash: certificate malformed"));
639 	  else
640 	    {
641 	      if (!handler->cert_get_key (cert, &key))
642 	        {
643 		  log_print ("rsa_sig_decode_hash: "
644 			     "decoding certificate failed");
645 		  handler->cert_free (cert);
646 		}
647 	      else
648 	        {
649 		  found++;
650 		  LOG_DBG ((LOG_CRYPTO, 40,
651 			    "rsa_sig_decode_hash: using cert of type %d",
652 			    handler->id));
653 		  exchange->recv_cert = cert;
654 		  exchange->recv_certtype = handler->id;
655 #if defined (USE_POLICY)
656 		  x509_generate_kn (exchange->policy_id, cert);
657 #endif /* USE_POLICY */
658 		}
659 	    }
660 	}
661       else if (handler->id == ISAKMP_CERTENC_KEYNOTE)
662 	handler->cert_insert (exchange->policy_id, rawcert);
663       free (rawcert);
664     }
665 
666   /*
667    * Walk over potential CERT payloads in this message.
668    * XXX I believe this is the wrong spot for this.  CERTs can appear
669    * anytime.
670    */
671   for (p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_CERT]); p;
672        p = TAILQ_NEXT (p, link))
673     {
674       p->flags |= PL_MARK;
675 
676       /* When we have found a key, just walk over the rest, marking them.  */
677       if (found)
678 	continue;
679 
680       handler = cert_get (GET_ISAKMP_CERT_ENCODING (p->p));
681       if (!handler)
682 	{
683 	  LOG_DBG ((LOG_MISC, 30,
684 		    "rsa_sig_decode_hash: no handler for %s CERT encoding",
685 		    constant_lookup (isakmp_certenc_cst,
686 				     GET_ISAKMP_CERT_ENCODING (p->p))));
687 	  continue;
688 	}
689 
690       cert = handler->cert_get (p->p + ISAKMP_CERT_DATA_OFF,
691 				GET_ISAKMP_GEN_LENGTH (p->p)
692 				- ISAKMP_CERT_DATA_OFF);
693       if (!cert)
694 	{
695 	  log_print ("rsa_sig_decode_hash: can not get data from CERT");
696 	  continue;
697 	}
698 
699       if (!handler->cert_validate (cert))
700 	{
701 	  handler->cert_free (cert);
702 	  log_print ("rsa_sig_decode_hash: received CERT can't be validated");
703 	  continue;
704 	}
705 
706       if (GET_ISAKMP_CERT_ENCODING (p->p) == ISAKMP_CERTENC_X509_SIG)
707         {
708 	  if (!handler->cert_get_subjects (cert, &n, &id_cert, &id_cert_len))
709 	    {
710 	      handler->cert_free (cert);
711 	      log_print ("rsa_sig_decode_hash: can not get subject from CERT");
712 	      continue;
713 	    }
714 
715 	  id_found = 0;
716 	  for (i = 0; i < n; i++)
717 	    if (id_cert_len[i] == id_len
718 		&& id[0] == id_cert[i][0]
719 		&& memcmp (id + 4, id_cert[i] + 4, id_len - 4) == 0)
720 	      {
721 		id_found++;
722 		break;
723 	      }
724 	  if (!id_found)
725 	    {
726 	      handler->cert_free (cert);
727 	      log_print ("rsa_sig_decode_hash: no CERT subject match the ID");
728 	      free (id_cert);
729 	      continue;
730 	    }
731 
732 	  cert_free_subjects (n, id_cert, id_cert_len);
733 	}
734 
735       if (!handler->cert_get_key (cert, &key))
736 	{
737 	  handler->cert_free (cert);
738 	  log_print ("rsa_sig_decode_hash: decoding payload CERT failed");
739 	  continue;
740 	}
741 
742       /* We validated the cert, cache it for later use.  */
743       handler->cert_insert (exchange->policy_id, cert);
744 
745       exchange->recv_cert = cert;
746       exchange->recv_certtype = GET_ISAKMP_CERT_ENCODING (p->p);
747 
748 #if defined (USE_POLICY) || defined (USE_KEYNOTE)
749       if (exchange->recv_certtype == ISAKMP_CERTENC_KEYNOTE)
750         {
751 	  struct keynote_deckey dc;
752 	  char *pp;
753 	  int dclen;
754 
755 	  dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
756 	  dc.dec_key = key;
757 
758 	  pp = kn_encode_key (&dc, INTERNAL_ENC_PKCS1, ENCODING_HEX,
759 			      KEYNOTE_PUBLIC_KEY);
760 	  if (pp == NULL)
761 	    {
762 	      kn_free_key (&dc);
763 	      log_print ("rsa_sig_decode_hash: failed to ASCII-encode key");
764 	      return -1;
765 	    }
766 
767 	  dclen = strlen (pp) + sizeof "rsa-hex:";
768 	  exchange->keynote_key = calloc (dclen, sizeof (char));
769 	  if (!exchange->keynote_key)
770 	    {
771 	      free (pp);
772 	      kn_free_key (&dc);
773 	      log_print ("rsa_sig_decode_hash: failed to allocate %d bytes",
774 			 dclen);
775 	      return -1;
776 	    }
777 
778 	  snprintf (exchange->keynote_key, dclen, "rsa-hex:%s", pp);
779 	  free (pp);
780 	}
781 #endif
782 
783       found++;
784     }
785 
786 #if defined (USE_DNSSEC)
787   /* If no certificate provided a key, try to find a validated DNSSEC KEY.  */
788   if (!found)
789     {
790       rawkey = dns_get_key (IKE_AUTH_RSA_SIG, msg, &rawkeylen);
791 
792       /* We need to convert 'void *rawkey' into 'RSA *key'.  */
793       if (dns_RSA_dns_to_x509 (rawkey, rawkeylen, &key) == 0)
794 	found++;
795       else
796 	log_print ("rsa_sig_decode_hash: KEY to RSA key conversion failed");
797 
798       if (rawkey)
799 	free (rawkey);
800     }
801 #endif /* USE_DNSSEC */
802 
803 #if defined (USE_RAWKEY)
804   /* If we still have not found a key, try to read it from a file. */
805   if (!found)
806     if (get_raw_key_from_file (IKE_AUTH_RSA_SIG, id, id_len, &key) != -1)
807       found++;
808 #endif
809 
810   if (!found)
811     {
812       log_print ("rsa_sig_decode_hash: no public key found");
813       return -1;
814     }
815 
816   p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_SIG]);
817   if (!p)
818     {
819       log_print ("rsa_sig_decode_hash: missing signature payload");
820       RSA_free (key);
821       return -1;
822     }
823 
824   /* Check that the sig is of the correct size.  */
825   len = GET_ISAKMP_GEN_LENGTH (p->p) - ISAKMP_SIG_SZ;
826   if (len != RSA_size (key))
827     {
828       RSA_free (key);
829       log_print ("rsa_sig_decode_hash: "
830 		 "SIG payload length does not match public key");
831       return -1;
832     }
833 
834   *hash_p = malloc (len);
835   if (!*hash_p)
836     {
837       RSA_free (key);
838       log_error ("rsa_sig_decode_hash: malloc (%d) failed", len);
839       return -1;
840     }
841 
842   len = RSA_public_decrypt (len, p->p + ISAKMP_SIG_DATA_OFF, *hash_p, key,
843 			    RSA_PKCS1_PADDING);
844   if (len == -1)
845     {
846       RSA_free (key);
847       log_print ("rsa_sig_decode_hash: RSA_public_decrypt () failed");
848       return -1;
849     }
850 
851   /* Store key for later use */
852   exchange->recv_key = key;
853   exchange->recv_keytype = ISAKMP_KEY_RSA;
854 
855   if (len != hashsize)
856     {
857       free (*hash_p);
858       *hash_p = 0;
859       log_print ("rsa_sig_decode_hash: len %lu != hashsize %lu",
860 	(unsigned long)len, (unsigned long)hashsize);
861       return -1;
862     }
863 
864   snprintf (header, sizeof header, "rsa_sig_decode_hash: HASH_%c",
865 	    initiator ? 'R' : 'I');
866   LOG_DBG_BUF ((LOG_MISC, 80, header, *hash_p, hashsize));
867 
868   p->flags |= PL_MARK;
869 
870   return 0;
871 }
872 #endif /* USE_X509 || USE_KEYNOTE */
873 
874 static int
875 pre_shared_encode_hash (struct message *msg)
876 {
877   struct exchange *exchange = msg->exchange;
878   struct ipsec_exch *ie = exchange->data;
879   size_t hashsize = ie->hash->hashsize;
880   char header[80];
881   int initiator = exchange->initiator;
882   u_int8_t *buf;
883 
884   buf = ipsec_add_hash_payload (msg, hashsize);
885   if (!buf)
886     return -1;
887 
888   if (ike_auth_hash (exchange, buf + ISAKMP_HASH_DATA_OFF) == -1)
889     return -1;
890 
891   snprintf (header, sizeof header, "pre_shared_encode_hash: HASH_%c",
892 	    initiator ? 'I' : 'R');
893   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_HASH_DATA_OFF, hashsize));
894   return 0;
895 }
896 
897 #if defined (USE_X509) || defined (USE_KEYNOTE)
898 /* Encrypt the HASH into a SIG type.  */
899 static int
900 rsa_sig_encode_hash (struct message *msg)
901 {
902   struct exchange *exchange = msg->exchange;
903   struct ipsec_exch *ie = exchange->data;
904   size_t hashsize = ie->hash->hashsize;
905   struct cert_handler *handler;
906   char header[80];
907   int initiator = exchange->initiator;
908   u_int8_t *buf, *data, *buf2;
909   u_int32_t datalen;
910   u_int8_t *id;
911   size_t id_len;
912   int idtype;
913   void *sent_key;
914 
915   id = initiator ? exchange->id_i : exchange->id_r;
916   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
917 
918   /* We may have been provided these by the kernel */
919   buf = (u_int8_t *)conf_get_str (exchange->name, "Credentials");
920   if (buf
921       && (idtype = conf_get_num (exchange->name, "Credential_Type", -1) != -1))
922     {
923       exchange->sent_certtype = idtype;
924       handler = cert_get (idtype);
925       if (!handler)
926 	{
927 	  log_print ("rsa_sig_encode_hash: cert_get (%d) failed", idtype);
928 	  return -1;
929 	}
930 
931       exchange->sent_cert = handler->cert_from_printable ((char *)buf);
932       if (!exchange->sent_cert)
933 	{
934 	  log_print ("rsa_sig_encode_hash: failed to retrieve certificate");
935 	  return -1;
936 	}
937 
938       handler->cert_serialize (exchange->sent_cert, &data, &datalen);
939       if (!data)
940 	{
941 	  log_print ("rsa_sig_encode_hash: cert serialization failed");
942 	  return -1;
943 	}
944 
945       goto aftercert; /* Skip all the certificate discovery */
946     }
947 
948   /* XXX This needs to be configurable.  */
949   idtype = ISAKMP_CERTENC_KEYNOTE;
950 
951   /* Find a certificate with subjectAltName = id.  */
952   handler = cert_get (idtype);
953   if (!handler)
954     {
955       idtype = ISAKMP_CERTENC_X509_SIG;
956       handler = cert_get (idtype);
957       if (!handler)
958 	{
959 	  log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
960 	  return -1;
961 	}
962     }
963 
964   if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
965     {
966       if (idtype == ISAKMP_CERTENC_KEYNOTE)
967 	{
968 	  idtype = ISAKMP_CERTENC_X509_SIG;
969 	  handler = cert_get (idtype);
970 	  if (!handler)
971 	    {
972 	      log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
973 	      return -1;
974 	    }
975 
976 	  if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
977 	    {
978 	      LOG_DBG ((LOG_MISC, 10,
979 			"rsa_sig_encode_hash: no certificate to send"));
980 	      goto skipcert;
981 	    }
982 	}
983       else
984 	{
985 	  LOG_DBG ((LOG_MISC, 10,
986 		    "rsa_sig_encode_hash: no certificate to send"));
987 	  goto skipcert;
988 	}
989     }
990 
991   /* Let's store the certificate we are going to use */
992   exchange->sent_certtype = idtype;
993   exchange->sent_cert = handler->cert_get (data, datalen);
994   if (!exchange->sent_cert)
995     {
996       free (data);
997       log_print ("rsa_sig_encode_hash: failed to get certificate from wire "
998 		 "encoding");
999       return -1;
1000     }
1001 
1002  aftercert:
1003 
1004   buf = realloc (data, ISAKMP_CERT_SZ + datalen);
1005   if (!buf)
1006     {
1007       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1008 		 ISAKMP_CERT_SZ + datalen);
1009       free (data);
1010       return -1;
1011     }
1012   memmove (buf + ISAKMP_CERT_SZ, buf, datalen);
1013   SET_ISAKMP_CERT_ENCODING (buf, idtype);
1014   if (message_add_payload (msg, ISAKMP_PAYLOAD_CERT, buf,
1015 			   ISAKMP_CERT_SZ + datalen, 1))
1016     {
1017       free (buf);
1018       return -1;
1019     }
1020 
1021  skipcert:
1022 
1023   /* Again, we may have these from the kernel */
1024   buf = (u_int8_t *)conf_get_str (exchange->name, "PKAuthentication");
1025   if (buf)
1026     {
1027       key_from_printable (ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE, (char *)buf,
1028 			  &data, &datalen);
1029       if (!data || datalen == -1)
1030 	{
1031 	  log_print ("rsa_sig_encode_hash: badly formatted RSA private key");
1032 	  return 0;
1033 	}
1034 
1035       sent_key = key_internalize (ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE, data,
1036 				  datalen);
1037       if (!sent_key)
1038 	{
1039 	  log_print ("rsa_sig_encode_hash: bad RSA private key from dynamic "
1040 		     "SA acquisition subsystem");
1041 	  return 0;
1042 	}
1043 #if defined (USE_PRIVSEP)
1044       {
1045 	/* With USE_PRIVSEP, the sent_key should be a key number. */
1046 	void *key = sent_key;
1047 	sent_key = monitor_RSA_upload_key (key);
1048       }
1049 #endif
1050     }
1051   else /* Try through the regular means.  */
1052     {
1053       switch (id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ])
1054 	{
1055 	case IPSEC_ID_IPV4_ADDR:
1056 	case IPSEC_ID_IPV6_ADDR:
1057 	  util_ntoa ((char **)&buf2,
1058 		     id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ] == IPSEC_ID_IPV4_ADDR
1059 		     ? AF_INET : AF_INET6,
1060 		     id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
1061 	  if (!buf2)
1062 	    return 0;
1063 	  break;
1064 
1065 	case IPSEC_ID_FQDN:
1066 	case IPSEC_ID_USER_FQDN:
1067 	  buf2 = calloc (id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1,
1068 			 sizeof (char));
1069 	  if (!buf2)
1070 	    {
1071 	      log_print ("rsa_sig_encode_hash: malloc (%lu) failed",
1072 			 (unsigned long)id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
1073 	      return 0;
1074 	    }
1075 	  memcpy (buf2, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
1076 		  id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
1077 	  break;
1078 
1079 	  /* XXX Support more ID types?  */
1080 	default:
1081 	  buf2 = 0;
1082 	  return 0;
1083 	}
1084 
1085 #if defined (USE_PRIVSEP)
1086       sent_key = monitor_RSA_get_private_key (exchange->name, (char *)buf2);
1087 #else
1088       sent_key = ike_auth_get_key (IKE_AUTH_RSA_SIG, exchange->name,
1089 				   (char *)buf2, 0);
1090 #endif
1091       free (buf2);
1092 
1093       /* Did we find a key?  */
1094       if (!sent_key)
1095 	{
1096 	  log_print ("rsa_sig_encode_hash: could not get private key");
1097 	  return -1;
1098 	}
1099     }
1100 
1101 #if !defined (USE_PRIVSEP)
1102   /* Enable RSA blinding.  */
1103   if (RSA_blinding_on (sent_key, NULL) != 1)
1104     {
1105       log_error ("rsa_sig_encode_hash: RSA_blinding_on () failed.");
1106       return -1;
1107     }
1108 #endif
1109 
1110   /* XXX hashsize is not necessarily prf->blocksize.  */
1111   buf = malloc (hashsize);
1112   if (!buf)
1113     {
1114       log_error ("rsa_sig_encode_hash: malloc (%lu) failed",
1115 	(unsigned long)hashsize);
1116       return -1;
1117     }
1118 
1119   if (ike_auth_hash (exchange, buf) == -1)
1120     {
1121       free (buf);
1122       return -1;
1123     }
1124 
1125   snprintf (header, sizeof header, "rsa_sig_encode_hash: HASH_%c",
1126 	    initiator ? 'I' : 'R');
1127   LOG_DBG_BUF ((LOG_MISC, 80, header, buf, hashsize));
1128 
1129 #if !defined (USE_PRIVSEP)
1130   data = malloc (RSA_size (sent_key));
1131   if (!data)
1132     {
1133       log_error ("rsa_sig_encode_hash: malloc (%d) failed",
1134 		 RSA_size (sent_key));
1135       return -1;
1136     }
1137 
1138   datalen = RSA_private_encrypt (hashsize, buf, data, sent_key,
1139 				 RSA_PKCS1_PADDING);
1140 #else
1141   datalen = monitor_RSA_private_encrypt (hashsize, buf, &data, sent_key,
1142 					 RSA_PKCS1_PADDING);
1143 #endif /* USE_PRIVSEP */
1144   if (datalen == -1)
1145     {
1146       log_print ("rsa_sig_encode_hash: RSA_private_encrypt () failed");
1147       if (data)
1148 	free (data);
1149       free (buf);
1150       monitor_RSA_free (sent_key);
1151       return -1;
1152     }
1153 
1154   free (buf);
1155 
1156   buf = realloc (data, ISAKMP_SIG_SZ + datalen);
1157   if (!buf)
1158     {
1159       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1160 		 ISAKMP_SIG_SZ + datalen);
1161       free (data);
1162       return -1;
1163     }
1164   memmove (buf + ISAKMP_SIG_SZ, buf, datalen);
1165 
1166   snprintf (header, sizeof header, "rsa_sig_encode_hash: SIG_%c",
1167 	    initiator ? 'I' : 'R');
1168   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_SIG_DATA_OFF, datalen));
1169   if (message_add_payload (msg, ISAKMP_PAYLOAD_SIG, buf,
1170 			   ISAKMP_SIG_SZ + datalen, 1))
1171     {
1172       free (buf);
1173       return -1;
1174     }
1175   return 0;
1176 }
1177 #endif /* USE_X509 || USE_KEYNOTE */
1178 
1179 int
1180 ike_auth_hash (struct exchange *exchange, u_int8_t *buf)
1181 {
1182   struct ipsec_exch *ie = exchange->data;
1183   struct prf *prf;
1184   struct hash *hash = ie->hash;
1185   int initiator = exchange->initiator;
1186   u_int8_t *id;
1187   size_t id_len;
1188 
1189   /* Choose the right fields to fill-in.  */
1190   id = initiator ? exchange->id_i : exchange->id_r;
1191   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
1192 
1193   /* Allocate the prf and start calculating our HASH.  */
1194   prf = prf_alloc (ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1195   if (!prf)
1196     return -1;
1197 
1198   prf->Init (prf->prfctx);
1199   prf->Update (prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1200   prf->Update (prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1201   prf->Update (prf->prfctx,
1202 	       exchange->cookies
1203 	       + (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1204 	       ISAKMP_HDR_ICOOKIE_LEN);
1205   prf->Update (prf->prfctx,
1206 	       exchange->cookies
1207 	       + (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1208 	       ISAKMP_HDR_ICOOKIE_LEN);
1209   prf->Update (prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1210   prf->Update (prf->prfctx, id, id_len);
1211   prf->Final (buf, prf->prfctx);
1212   prf_free (prf);
1213 
1214   return 0;
1215 }
1216 
1217 #if defined (USE_RAWKEY)
1218 static int
1219 get_raw_key_from_file (int type, u_int8_t *id, size_t id_len, RSA **rsa)
1220 {
1221   char filename[FILENAME_MAX];
1222   char *fstr;
1223   struct stat st;
1224   BIO *bio;
1225 
1226   if (type != IKE_AUTH_RSA_SIG) /* XXX More types? */
1227     {
1228       LOG_DBG ((LOG_NEGOTIATION, 20, "get_raw_key_from_file: "
1229 		"invalid auth type %d\n", type));
1230       return -1;
1231     }
1232 
1233   *rsa = 0;
1234 
1235   fstr = conf_get_str ("General", "Pubkey-directory");
1236   if (!fstr)
1237     fstr = CONF_DFLT_PUBKEY_DIR;
1238 
1239   if (snprintf (filename, sizeof filename, "%s/", fstr) > sizeof filename - 1)
1240     return -1;
1241 
1242   fstr = ipsec_id_string (id, id_len);
1243   if (!fstr)
1244     {
1245       LOG_DBG ((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1246 		"ipsec_id_string failed"));
1247       return -1;
1248     }
1249   strlcat (filename, fstr, sizeof filename - strlen (filename));
1250   free (fstr);
1251 
1252   /* If the file does not exist, fail silently.  */
1253   if (stat (filename, &st) == 0)
1254     {
1255       bio = BIO_new (BIO_s_file ());
1256       if (!bio)
1257 	{
1258 	  log_error ("get_raw_key_from_file: could not initialize BIO");
1259 	  return -1;
1260 	}
1261       if (BIO_read_filename (bio, filename) <= 0)
1262 	{
1263 	  LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1264 		   "BIO_read_filename(bio, \"%s\") failed", filename));
1265 	  BIO_free (bio);
1266 	  return -1;
1267 	}
1268       LOG_DBG((LOG_NEGOTIATION, 80, "get_raw_key_from_file: reading file %s",
1269 	       filename));
1270       *rsa = PEM_read_bio_RSA_PUBKEY (bio, NULL, NULL, NULL);
1271       BIO_free (bio);
1272     }
1273   else
1274     LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: file %s not found",
1275 	     filename));
1276 
1277   return (*rsa ? 0 : -1);
1278 }
1279 #endif /* USE_RAWKEY */
1280