xref: /openbsd-src/sbin/isakmpd/ike_auth.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: ike_auth.c,v 1.54 2001/08/15 13:06:53 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 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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by Ericsson Radio Systems.
21  * 4. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /*
37  * This code was written under funding by Ericsson Radio Systems.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <regex.h>
49 #if defined (USE_KEYNOTE)
50 #include <keynote.h>
51 #endif
52 #include <policy.h>
53 
54 #include "sysdep.h"
55 
56 #include "cert.h"
57 #include "conf.h"
58 #include "constants.h"
59 #if defined (USE_DNSSEC)
60 #include "dnssec.h"
61 #endif
62 #include "exchange.h"
63 #include "gmp_util.h"
64 #include "hash.h"
65 #include "ike_auth.h"
66 #include "ipsec.h"
67 #include "ipsec_doi.h"
68 #include "libcrypto.h"
69 #include "log.h"
70 #include "message.h"
71 #include "prf.h"
72 #include "transport.h"
73 #include "util.h"
74 #include "key.h"
75 #if defined (USE_X509)
76 #include "x509.h"
77 #endif
78 
79 #ifdef notyet
80 static u_int8_t *enc_gen_skeyid (struct exchange *, size_t *);
81 #endif
82 static u_int8_t *pre_shared_gen_skeyid (struct exchange *, size_t *);
83 
84 static int pre_shared_decode_hash (struct message *);
85 static int pre_shared_encode_hash (struct message *);
86 
87 #if defined (USE_X509) || defined (USE_KEYNOTE)
88 static u_int8_t *sig_gen_skeyid (struct exchange *, size_t *);
89 static int rsa_sig_decode_hash (struct message *);
90 static int rsa_sig_encode_hash (struct message *);
91 #endif
92 
93 #if defined (USE_RAWKEY)
94 #define PUBKEY_DIR_DEFAULT "/etc/isakmpd/pubkeys"
95 static int get_raw_key_from_file (int, u_int8_t *, size_t, RSA **);
96 #endif
97 
98 static int ike_auth_hash (struct exchange *, u_int8_t *);
99 
100 static struct ike_auth ike_auth[] = {
101   {
102     IKE_AUTH_PRE_SHARED, pre_shared_gen_skeyid, pre_shared_decode_hash,
103     pre_shared_encode_hash
104   },
105 #ifdef notdef
106   {
107     IKE_AUTH_DSS, sig_gen_skeyid, pre_shared_decode_hash,
108     pre_shared_encode_hash
109   },
110 #endif
111 #if defined (USE_X509) || defined (USE_KEYNOTE)
112   {
113     IKE_AUTH_RSA_SIG, sig_gen_skeyid, rsa_sig_decode_hash,
114     rsa_sig_encode_hash
115   },
116 #endif
117 #ifdef notdef
118   {
119     IKE_AUTH_RSA_ENC, enc_gen_skeyid, pre_shared_decode_hash,
120     pre_shared_encode_hash
121   },
122   {
123     IKE_AUTH_RSA_ENC_REV, enc_gen_skeyid, pre_shared_decode_hash,
124     pre_shared_encode_hash
125   },
126 #endif
127 };
128 
129 struct ike_auth *
130 ike_auth_get (u_int16_t id)
131 {
132   int i;
133 
134   for (i = 0; i < sizeof ike_auth / sizeof ike_auth[0]; i++)
135     if (id == ike_auth[i].id)
136       return &ike_auth[i];
137   return 0;
138 }
139 
140 /*
141  * Find and decode the configured key (pre-shared or public) for the
142  * peer denoted by ID.  Stash the len in KEYLEN.
143  */
144 static void *
145 ike_auth_get_key (int type, char *id, char *local_id, size_t *keylen)
146 {
147   char *key, *buf;
148 #if defined (USE_X509) || defined (USE_KEYNOTE)
149   char *keyfile;
150 #if defined (USE_X509)
151   BIO *keyh;
152   RSA *rsakey;
153 #endif
154 #endif
155 
156   switch (type)
157     {
158     case IKE_AUTH_PRE_SHARED:
159       /* Get the pre-shared key for our peer.  */
160       key = conf_get_str (id, "Authentication");
161       if (!key && local_id)
162 	key = conf_get_str (local_id, "Authentication");
163 
164       if (!key)
165         {
166 	  log_print ("ike_auth_get_key: "
167 		     "no key found for peer \"%s\"or local ID \"%s\"",
168 		     id, local_id);
169 	  return 0;
170 	}
171 
172       /* If the key starts with 0x it is in hex format.  */
173       if (strncasecmp (key, "0x", 2) == 0)
174 	{
175 	  *keylen = (strlen (key) - 1) / 2;
176 	  buf = malloc (*keylen);
177 	  if (!buf)
178 	    {
179 	      log_print ("ike_auth_get_key: malloc (%d) failed", *keylen);
180 	      return 0;
181 	    }
182 	  if (hex2raw (key + 2, buf, *keylen))
183 	    {
184 	      free (buf);
185 	      log_print ("ike_auth_get_key: invalid hex key %s", key);
186 	      return 0;
187 	    }
188 	  key = buf;
189 	}
190       else
191 	*keylen = strlen (key);
192       break;
193 
194     case IKE_AUTH_RSA_SIG:
195 #if defined (USE_X509) || defined (USE_KEYNOTE)
196 #ifdef HAVE_DLOPEN
197       if (!libcrypto)
198 	return 0;
199 #endif
200 #if defined (USE_KEYNOTE)
201       if (local_id &&
202 	  (keyfile = conf_get_str ("KeyNote", "Credential-directory")) != 0)
203         {
204 	  struct stat sb;
205 	  struct keynote_deckey dc;
206 	  char *privkeyfile, *buf2;
207 	  int fd;
208 
209 	  privkeyfile = calloc (strlen (keyfile) + strlen (local_id)
210 				+ sizeof PRIVATE_KEY_FILE + sizeof "//" - 1,
211 				sizeof (char));
212 	  if (!privkeyfile)
213 	    {
214 	      log_print ("ike_auth_get_key: failed to allocate %d bytes",
215 			 strlen (keyfile) + strlen (local_id)
216 			 + sizeof PRIVATE_KEY_FILE + sizeof "//" - 1);
217 	      return 0;
218 	    }
219 
220 	  sprintf (privkeyfile, "%s/%s/%s", keyfile, local_id,
221 		   PRIVATE_KEY_FILE);
222 	  keyfile = privkeyfile;
223 
224 	  if (stat (keyfile, &sb) < 0)
225 	    {
226 	      free (keyfile);
227 	      goto ignorekeynote;
228 	    }
229 
230 	  fd = open (keyfile, O_RDONLY, 0);
231 	  if (fd < 0)
232 	    {
233 	      log_print ("ike_auth_get_key: failed opening \"%s\"", keyfile);
234 	      free (keyfile);
235 	      return 0;
236 	    }
237 
238 	  buf = calloc (sb.st_size + 1, sizeof (char));
239 	  if (!buf)
240 	    {
241 	      log_print ("ike_auth_get_key: failed allocating %d bytes",
242 			 sb.st_size + 1);
243 	      free (keyfile);
244 	      return 0;
245 	    }
246 
247 	  if (read (fd, buf, sb.st_size) != sb.st_size)
248 	    {
249 	      free (buf);
250 	      log_print ("ike_auth_get_key: "
251 			 "failed reading %d bytes from \"%s\"",
252 			 sb.st_size, keyfile);
253 	      free (keyfile);
254 	      return 0;
255 	    }
256 
257 	  close (fd);
258 
259 	  /* Parse private key string */
260 	  buf2 = kn_get_string (buf);
261 	  free (buf);
262 
263 	  if (LK (kn_decode_key, (&dc, buf2, KEYNOTE_PRIVATE_KEY)) == -1)
264 	    {
265 	      free (buf2);
266 	      log_print ("ike_auth_get_key: failed decoding key in \"%s\"",
267 			 keyfile);
268 	      free (keyfile);
269 	      return 0;
270 	    }
271 
272 	  free (buf2);
273 
274 	  if (dc.dec_algorithm != KEYNOTE_ALGORITHM_RSA)
275 	    {
276 	      log_print ("ike_auth_get_key: wrong algorithm type %d in \"%s\"",
277 			 dc.dec_algorithm, keyfile);
278 	      free (keyfile);
279 	      LK (kn_free_key, (&dc));
280 	      return 0;
281 	    }
282 
283 	  free (keyfile);
284 	  return dc.dec_key;
285 	}
286 
287     ignorekeynote:
288 #endif /* USE_KEYNOTE */
289 #ifdef USE_X509
290       /* Otherwise, try X.509 */
291       keyfile = conf_get_str ("X509-certificates", "Private-key");
292 
293       if (check_file_secrecy (keyfile, 0))
294 	return 0;
295 
296       keyh = LC (BIO_new, (LC (BIO_s_file, ())));
297       if (keyh == NULL)
298 	{
299 	  log_print ("ike_auth_get_key: "
300 		     "BIO_new (BIO_s_file ()) failed");
301 	  return 0;
302 	}
303       if (LC (BIO_read_filename, (keyh, keyfile)) == -1)
304 	{
305 	  log_print ("ike_auth_get_key: "
306 		     "BIO_read_filename (keyh, \"%s\") failed",
307 		     keyfile);
308 	  LC (BIO_free, (keyh));
309 	  return 0;
310 	}
311 
312 #if SSLEAY_VERSION_NUMBER >= 0x00904100L
313       rsakey = LC (PEM_read_bio_RSAPrivateKey, (keyh, NULL, NULL, NULL));
314 #else
315       rsakey = LC (PEM_read_bio_RSAPrivateKey, (keyh, NULL, NULL));
316 #endif
317       LC (BIO_free, (keyh));
318       if (!rsakey)
319 	{
320 	  log_print ("ike_auth_get_key: PEM_read_bio_RSAPrivateKey failed");
321 	  return 0;
322 	}
323 
324       return rsakey;
325 #endif
326 #endif
327 
328     default:
329       log_print ("ike_auth_get_key: unknown key type %d", type);
330       return 0;
331     }
332 
333   return key;
334 }
335 
336 static u_int8_t *
337 pre_shared_gen_skeyid (struct exchange *exchange, size_t *sz)
338 {
339   struct prf *prf;
340   struct ipsec_exch *ie = exchange->data;
341   u_int8_t *skeyid;
342   u_int8_t *key;
343   u_int8_t *buf = 0;
344   size_t keylen;
345 
346   /*
347    * If we're the responder and have the initiator's ID (which is the
348    * case in Aggressive mode), try to find the preshared key in the
349    * section of the initiator's Phase 1 ID.  This allows us to do
350    * mobile user support with preshared keys.
351    */
352   if (!exchange->initiator && exchange->id_i)
353     {
354       switch (exchange->id_i[0])
355         {
356 	case IPSEC_ID_IPV4_ADDR:
357 	case IPSEC_ID_IPV6_ADDR:
358 	  util_ntoa ((char **)&buf,
359 		     exchange->id_i[0] == IPSEC_ID_IPV4_ADDR
360 		     ? AF_INET : AF_INET6,
361 		     exchange->id_i + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
362 	  if (!buf)
363 	    return 0;
364 	  break;
365 
366 	case IPSEC_ID_FQDN:
367 	case IPSEC_ID_USER_FQDN:
368 	  buf = calloc (exchange->id_i_len - ISAKMP_ID_DATA_OFF
369 			+ ISAKMP_GEN_SZ + 1, sizeof (char));
370 	  if (!buf)
371 	    {
372               log_print ("pre_shared_gen_skeyid: malloc (%d) failed",
373 			 exchange->id_i_len - ISAKMP_ID_DATA_OFF
374 			 + ISAKMP_GEN_SZ + 1);
375 	      return 0;
376 	    }
377 	  memcpy (buf, exchange->id_i + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
378 		  exchange->id_i_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
379 	  break;
380 
381 	  /* XXX Support more ID types ? */
382 	default:
383 	  break;
384 	}
385     }
386 
387   /*
388    * Get the pre-shared key for our peer. This will work even if the key
389    * has been passed to us through a mechanism like PFKEYv2.
390    */
391   key = ike_auth_get_key (IKE_AUTH_PRE_SHARED, exchange->name, buf, &keylen);
392   if (buf)
393     free (buf);
394 
395   /* Fail if no key could be found.  */
396   if (!key)
397     return 0;
398 
399   /* Store the secret key for later policy processing.  */
400   exchange->recv_key = calloc (keylen + 1, sizeof (char));
401   exchange->recv_keytype = ISAKMP_KEY_PASSPHRASE;
402   if (!exchange->recv_key)
403     {
404       log_error ("pre_shared_gen_skeyid: malloc (%d) failed", keylen);
405       return 0;
406     }
407   memcpy (exchange->recv_key, key, keylen);
408   exchange->recv_certtype = ISAKMP_CERTENC_NONE;
409 
410   prf = prf_alloc (ie->prf_type, ie->hash->type, key, keylen);
411   if (!prf)
412     return 0;
413 
414   *sz = prf->blocksize;
415   skeyid = malloc (*sz);
416   if (!skeyid)
417     {
418       log_error ("pre_shared_gen_skeyid: malloc (%d) failed", *sz);
419       prf_free (prf);
420       return 0;
421     }
422 
423   prf->Init (prf->prfctx);
424   prf->Update (prf->prfctx, exchange->nonce_i, exchange->nonce_i_len);
425   prf->Update (prf->prfctx, exchange->nonce_r, exchange->nonce_r_len);
426   prf->Final (skeyid, prf->prfctx);
427   prf_free (prf);
428 
429   return skeyid;
430 }
431 
432 #if defined (USE_X509) || defined (USE_KEYNOTE)
433 /* Both DSS & RSA signature authentication use this algorithm.  */
434 static u_int8_t *
435 sig_gen_skeyid (struct exchange *exchange, size_t *sz)
436 {
437   struct prf *prf;
438   struct ipsec_exch *ie = exchange->data;
439   u_int8_t *skeyid, *key;
440 
441   key = malloc (exchange->nonce_i_len + exchange->nonce_r_len);
442   if (!key)
443     return 0;
444   memcpy (key, exchange->nonce_i, exchange->nonce_i_len);
445   memcpy (key + exchange->nonce_i_len, exchange->nonce_r,
446 	  exchange->nonce_r_len);
447 
448   LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: PRF type %d, hash %d",
449       ie->prf_type, ie->hash->type));
450   LOG_DBG_BUF((LOG_NEGOTIATION, 80, "sig_gen_skeyid: SKEYID initialized with",
451       key, exchange->nonce_i_len + exchange->nonce_r_len));
452 
453   prf = prf_alloc (ie->prf_type, ie->hash->type, key,
454 		   exchange->nonce_i_len + exchange->nonce_r_len);
455   free (key);
456   if (!prf)
457     return 0;
458 
459   *sz = prf->blocksize;
460   skeyid = malloc (*sz);
461   if (!skeyid)
462     {
463       log_error ("sig_gen_skeyid: malloc (%d) failed", *sz);
464       prf_free (prf);
465       return 0;
466     }
467 
468   LOG_DBG((LOG_NEGOTIATION, 80, "sig_gen_skeyid: g^xy length %d",
469       ie->g_x_len));
470   LOG_DBG_BUF((LOG_NEGOTIATION, 80,
471       "sig_gen_skeyid: SKEYID fed with g^xy", 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 (%d) failed", hashsize);
551       return -1;
552     }
553 
554   memcpy (*hash_p, payload->p + ISAKMP_HASH_DATA_OFF, hashsize);
555   snprintf (header, 80, "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 = LK (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 
754 	  dc.dec_algorithm = KEYNOTE_ALGORITHM_RSA;
755 	  dc.dec_key = key;
756 
757 	  pp = LK (kn_encode_key, (&dc, INTERNAL_ENC_PKCS1, ENCODING_HEX,
758 				   KEYNOTE_PUBLIC_KEY));
759 	  if (pp == NULL)
760 	    {
761 	      LK (kn_free_key, (&dc));
762 	      log_print ("rsa_sig_decode_hash: failed to ASCII-encode key");
763 	      return -1;
764 	    }
765 
766 	  exchange->keynote_key = calloc (strlen (pp) + sizeof "rsa-hex:",
767 					  sizeof (char));
768 	  if (!exchange->keynote_key)
769 	    {
770 	      free (pp);
771 	      LK (kn_free_key, (&dc));
772 	      log_print ("rsa_sig_decode_hash: failed to allocate %d bytes",
773 			 strlen (pp) + sizeof "rsa-hex:");
774 	      return -1;
775 	    }
776 
777 	  sprintf (exchange->keynote_key, "rsa-hex:%s", pp);
778 	  free (pp);
779 	}
780 #endif
781 
782       found++;
783     }
784 
785 #if defined (USE_DNSSEC)
786   /* If no certificate provided a key, try to find a validated DNSSEC KEY.  */
787   if (!found)
788     {
789       rawkey = dns_get_key (IKE_AUTH_RSA_SIG, msg, &rawkeylen);
790       if (rawkey)
791 	found++;
792 
793       /* We need to convert 'void *rawkey' into 'RSA *key'.  */
794       if (dns_RSA_dns_to_x509 (rawkey, rawkeylen, &key) == -1)
795 	{
796 	  log_print ("rsa_sig_decode_hash: KEY to RSA key conversion failed");
797 	  free (rawkey);
798 	  return -1;
799 	}
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       LC (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 != LC (RSA_size, (key)))
828     {
829       LC (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       LC (RSA_free, (key));
839       log_error ("rsa_sig_decode_hash: malloc (%d) failed", len);
840       return -1;
841     }
842 
843   len = LC (RSA_public_decrypt, (len, p->p + ISAKMP_SIG_DATA_OFF, *hash_p, key,
844 				 RSA_PKCS1_PADDING));
845   if (len == -1)
846     {
847       LC (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 %d != hashsize %d", len, hashsize);
861       return -1;
862     }
863 
864   snprintf (header, 80, "rsa_sig_decode_hash: HASH_%c", initiator ? 'R' : 'I');
865   LOG_DBG_BUF ((LOG_MISC, 80, header, *hash_p, hashsize));
866 
867   p->flags |= PL_MARK;
868 
869   return 0;
870 }
871 #endif /* USE_X509 || USE_KEYNOTE */
872 
873 static int
874 pre_shared_encode_hash (struct message *msg)
875 {
876   struct exchange *exchange = msg->exchange;
877   struct ipsec_exch *ie = exchange->data;
878   size_t hashsize = ie->hash->hashsize;
879   char header[80];
880   int initiator = exchange->initiator;
881   u_int8_t *buf;
882 
883   buf = ipsec_add_hash_payload (msg, hashsize);
884   if (!buf)
885     return -1;
886 
887   if (ike_auth_hash (exchange, buf + ISAKMP_HASH_DATA_OFF) == -1)
888     return -1;
889 
890   snprintf (header, 80, "pre_shared_encode_hash: HASH_%c",
891 	    initiator ? 'I' : 'R');
892   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_HASH_DATA_OFF, hashsize));
893   return 0;
894 }
895 
896 #if defined (USE_X509) || defined (USE_KEYNOTE)
897 /* Encrypt the HASH into a SIG type.  */
898 static int
899 rsa_sig_encode_hash (struct message *msg)
900 {
901   struct exchange *exchange = msg->exchange;
902   struct ipsec_exch *ie = exchange->data;
903   size_t hashsize = ie->hash->hashsize;
904   struct cert_handler *handler;
905   char header[80];
906   int initiator = exchange->initiator;
907   u_int8_t *buf, *data, *buf2;
908   u_int32_t datalen;
909   u_int8_t *id;
910   size_t id_len;
911   int idtype;
912 
913   id = initiator ? exchange->id_i : exchange->id_r;
914   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
915 
916   /* We may have been provided these by the kernel */
917   buf = conf_get_str (exchange->name, "Credentials");
918   if (buf
919       && (idtype = conf_get_num (exchange->name, "Credential_Type", -1) != -1))
920     {
921       exchange->sent_certtype = idtype;
922       handler = cert_get (idtype);
923       if (!handler)
924 	{
925 	  log_print ("rsa_sig_encode_hash: cert_get (%d) failed", idtype);
926 	  return -1;
927 	}
928 
929       exchange->sent_cert = handler->cert_from_printable (buf);
930       if (!exchange->sent_cert)
931 	{
932 	  log_print ("rsa_sig_encode_hash: failed to retrieve certificate");
933 	  return -1;
934 	}
935 
936       handler->cert_serialize (exchange->sent_cert, &data, &datalen);
937       if (!data)
938 	{
939 	  log_print ("rsa_sig_encode_hash: cert serialization failed");
940 	  return -1;
941 	}
942 
943       goto aftercert; /* Skip all the certificate discovery */
944     }
945 
946   /* XXX This needs to be configurable.  */
947   idtype = ISAKMP_CERTENC_KEYNOTE;
948 
949   /* Find a certificate with subjectAltName = id.  */
950   handler = cert_get (idtype);
951   if (!handler)
952     {
953       idtype = ISAKMP_CERTENC_X509_SIG;
954       handler = cert_get (idtype);
955       if (!handler)
956 	{
957 	  log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
958 	  return -1;
959 	}
960     }
961 
962   if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
963     {
964       if (idtype == ISAKMP_CERTENC_KEYNOTE)
965 	{
966 	  idtype = ISAKMP_CERTENC_X509_SIG;
967 	  handler = cert_get (idtype);
968 	  if (!handler)
969 	    {
970 	      log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
971 	      return -1;
972 	    }
973 
974 	  if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
975 	    {
976 	      LOG_DBG ((LOG_MISC, 10,
977 			"rsa_sig_encode_hash: no certificate to send"));
978 	      goto skipcert;
979 	    }
980 	}
981       else
982 	{
983 	  LOG_DBG ((LOG_MISC, 10,
984 		    "rsa_sig_encode_hash: no certificate to send"));
985 	  goto skipcert;
986 	}
987     }
988 
989   /* Let's store the certificate we are going to use */
990   exchange->sent_certtype = idtype;
991   exchange->sent_cert = handler->cert_get (data, datalen);
992   if (!exchange->sent_cert)
993     {
994       free (data);
995       log_print ("rsa_sig_encode_hash: failed to get certificate from wire "
996 		 "encoding");
997       return -1;
998     }
999 
1000  aftercert:
1001 
1002   buf = realloc (data, ISAKMP_CERT_SZ + datalen);
1003   if (!buf)
1004     {
1005       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1006 		 ISAKMP_CERT_SZ + datalen);
1007       free (data);
1008       return -1;
1009     }
1010   memmove (buf + ISAKMP_CERT_SZ, buf, datalen);
1011   SET_ISAKMP_CERT_ENCODING (buf, idtype);
1012   if (message_add_payload (msg, ISAKMP_PAYLOAD_CERT, buf,
1013 			   ISAKMP_CERT_SZ + datalen, 1))
1014     {
1015       free (buf);
1016       return -1;
1017     }
1018 
1019  skipcert:
1020 
1021   switch (id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ])
1022     {
1023     case IPSEC_ID_IPV4_ADDR:
1024     case IPSEC_ID_IPV6_ADDR:
1025       util_ntoa ((char **)&buf2,
1026 		 id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ] == IPSEC_ID_IPV4_ADDR
1027 		 ? AF_INET : AF_INET6,
1028 		 id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
1029       if (!buf2)
1030 	return 0;
1031       break;
1032 
1033     case IPSEC_ID_FQDN:
1034     case IPSEC_ID_USER_FQDN:
1035       buf2 = calloc (id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1,
1036 		     sizeof (char));
1037       if (!buf2)
1038         {
1039 	  log_print ("rsa_sig_encode_hash: malloc (%d) failed",
1040 		     id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
1041 	  return 0;
1042 	}
1043       memcpy (buf2, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
1044 	      id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
1045       break;
1046 
1047       /* XXX Support more ID types?  */
1048     default:
1049       buf2 = 0;
1050       break;
1051     }
1052 
1053   /* Again, we may have these from the kernel */
1054   buf = conf_get_str (exchange->name, "OKAuthentication");
1055   if (buf)
1056     {
1057       key_from_printable (ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE, buf, &data,
1058 			  &datalen);
1059       if (!data || datalen == -1)
1060 	{
1061 	  log_print ("rsa_sig_encode_hash: badly formatted RSA private key");
1062 	  return 0;
1063 	}
1064 
1065       exchange->sent_keytype = ISAKMP_KEY_RSA;
1066       exchange->sent_key = key_internalize (ISAKMP_KEY_RSA,
1067 					    ISAKMP_KEYTYPE_PRIVATE, data,
1068 					    datalen);
1069       if (!exchange->sent_key)
1070 	{
1071 	  log_print ("rsa_sig_encode_hash: bad RSA private key from dynamic "
1072 		     "SA acquisition subsystem");
1073 	  return 0;
1074 	}
1075     }
1076   else /* Try through the regular means.  */
1077     {
1078       exchange->sent_key = ike_auth_get_key (IKE_AUTH_RSA_SIG, exchange->name,
1079 					     buf2, 0);
1080       free (buf2);
1081 
1082       /* Did we find a key?  */
1083       if (!exchange->sent_key)
1084 	{
1085 	  log_print ("rsa_sig_encode_hash: could not get private key");
1086 	  return -1;
1087 	}
1088 
1089       exchange->sent_keytype = ISAKMP_KEY_RSA;
1090     }
1091 
1092   /* XXX hashsize is not necessarily prf->blocksize.  */
1093   buf = malloc (hashsize);
1094   if (!buf)
1095     {
1096       log_error ("rsa_sig_encode_hash: malloc (%d) failed", hashsize);
1097       return -1;
1098     }
1099 
1100   if (ike_auth_hash (exchange, buf) == -1)
1101     {
1102       free (buf);
1103       return -1;
1104     }
1105 
1106   snprintf (header, 80, "rsa_sig_encode_hash: HASH_%c", initiator ? 'I' : 'R');
1107   LOG_DBG_BUF ((LOG_MISC, 80, header, buf, hashsize));
1108 
1109   data = malloc (LC (RSA_size, (exchange->sent_key)));
1110   if (!data)
1111     {
1112       log_error ("rsa_sig_encode_hash: malloc (%d) failed",
1113 		 LC (RSA_size, (exchange->sent_key)));
1114       return -1;
1115     }
1116 
1117   datalen = LC (RSA_private_encrypt, (hashsize, buf, data,
1118 				      exchange->sent_key, RSA_PKCS1_PADDING));
1119   if (datalen == -1)
1120     {
1121       log_print ("rsa_sig_encode_hash: RSA_private_encrypt () failed");
1122       free (buf);
1123       return -1;
1124     }
1125 
1126   free (buf);
1127 
1128   buf = realloc (data, ISAKMP_SIG_SZ + datalen);
1129   if (!buf)
1130     {
1131       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1132 		 ISAKMP_SIG_SZ + datalen);
1133       free (data);
1134       return -1;
1135     }
1136   memmove (buf + ISAKMP_SIG_SZ, buf, datalen);
1137 
1138   snprintf (header, 80, "rsa_sig_encode_hash: SIG_%c", initiator ? 'I' : 'R');
1139   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_SIG_DATA_OFF, datalen));
1140   if (message_add_payload (msg, ISAKMP_PAYLOAD_SIG, buf,
1141 			   ISAKMP_SIG_SZ + datalen, 1))
1142     {
1143       free (buf);
1144       return -1;
1145     }
1146   return 0;
1147 }
1148 #endif /* USE_X509 || USE_KEYNOTE */
1149 
1150 int
1151 ike_auth_hash (struct exchange *exchange, u_int8_t *buf)
1152 {
1153   struct ipsec_exch *ie = exchange->data;
1154   struct prf *prf;
1155   struct hash *hash = ie->hash;
1156   int initiator = exchange->initiator;
1157   u_int8_t *id;
1158   size_t id_len;
1159 
1160   /* Choose the right fields to fill-in.  */
1161   id = initiator ? exchange->id_i : exchange->id_r;
1162   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
1163 
1164   /* Allocate the prf and start calculating our HASH.  */
1165   prf = prf_alloc (ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1166   if (!prf)
1167     return -1;
1168 
1169   prf->Init (prf->prfctx);
1170   prf->Update (prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1171   prf->Update (prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1172   prf->Update (prf->prfctx,
1173 	       exchange->cookies
1174 	       + (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1175 	       ISAKMP_HDR_ICOOKIE_LEN);
1176   prf->Update (prf->prfctx,
1177 	       exchange->cookies
1178 	       + (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1179 	       ISAKMP_HDR_ICOOKIE_LEN);
1180   prf->Update (prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1181   prf->Update (prf->prfctx, id, id_len);
1182   prf->Final (buf, prf->prfctx);
1183   prf_free (prf);
1184 
1185   return 0;
1186 }
1187 
1188 #if defined (USE_RAWKEY)
1189 static int
1190 get_raw_key_from_file (int type, u_int8_t *id, size_t id_len, RSA **rsa)
1191 {
1192   char filename[FILENAME_MAX];
1193   char *rdir, *base, *addrstr = 0;
1194   struct stat st;
1195   FILE *fp;
1196 
1197   if (type != IKE_AUTH_RSA_SIG) /* XXX More types? */
1198     {
1199       LOG_DBG ((LOG_NEGOTIATION, 20, "get_raw_key_from_file: "
1200 		"invalid auth type %d\n", type));
1201       return -1;
1202     }
1203 
1204   *rsa = 0;
1205 
1206   rdir = conf_get_str ("General", "Pubkey-directory");
1207   if (!rdir)
1208     rdir = PUBKEY_DIR_DEFAULT;
1209 
1210   strncpy (filename, rdir, FILENAME_MAX - 1);
1211   filename[FILENAME_MAX - 1] = '\0';
1212   base = filename + strlen (filename) - 1;
1213 
1214   switch (GET_ISAKMP_ID_TYPE (id))
1215     {
1216     case IPSEC_ID_IPV4_ADDR:
1217       if (id_len < sizeof (struct in_addr))
1218 	return -1;
1219       util_ntoa (&addrstr, AF_INET, id + ISAKMP_ID_DATA_OFF);
1220       if (!addrstr)
1221 	return -1;
1222       strncat (filename, "/ipv4/", FILENAME_MAX - 1 - strlen (filename));
1223       strncat (filename, addrstr, FILENAME_MAX - 1 - strlen (filename));
1224       break;
1225 
1226     case IPSEC_ID_IPV6_ADDR:
1227       if (id_len < sizeof (struct in6_addr))
1228 	return -1;
1229       util_ntoa (&addrstr, AF_INET6, id + ISAKMP_ID_DATA_OFF);
1230       if (!addrstr)
1231 	return -1;
1232       strncat (filename, "/ipv6/", FILENAME_MAX - 1 - strlen (filename));
1233       strncat (filename, addrstr, FILENAME_MAX - 1 - strlen (filename));
1234       break;
1235 
1236     case IPSEC_ID_FQDN:
1237     case IPSEC_ID_USER_FQDN:
1238       if (GET_ISAKMP_ID_TYPE (id) == IPSEC_ID_FQDN)
1239 	addrstr = "/fqdn/";
1240       else
1241 	addrstr = "/ufqdn/";
1242 
1243       strncat (filename, addrstr, FILENAME_MAX - 1 - strlen (filename));
1244 
1245       /* Id is not NULL-terminated.  */
1246       id_len -= ISAKMP_ID_DATA_OFF;
1247       id_len = MIN (id_len, FILENAME_MAX - 1 - strlen (filename));
1248       memcpy (base + strlen (addrstr), id + ISAKMP_ID_DATA_OFF, id_len);
1249       *(base + strlen (addrstr) + id_len) = '\0';
1250       addrstr = 0;
1251       break;
1252 
1253     default:
1254       /* Unknown type.  */
1255       LOG_DBG ((LOG_NEGOTIATION, 10, "get_raw_key_from_file: "
1256 		"unknown identity type %d\n", GET_ISAKMP_ID_TYPE (id)));
1257       return -1;
1258       break;
1259     }
1260 
1261   /* If the file does not exist, fail silently.  */
1262   if (stat (filename, &st) == 0)
1263     {
1264       fp = fopen (filename, "r");
1265       if (!fp)
1266 	{
1267 	  log_error ("get_raw_key_from_file: could not open \"%s\"", filename);
1268 	  goto out;
1269 	}
1270       *rsa = LC (PEM_read_RSAPublicKey, (fp, NULL, NULL, NULL));
1271       fclose (fp);
1272     }
1273 
1274  out:
1275   if (addrstr)
1276     free (addrstr);
1277 
1278   return (*rsa ? 0 : -1);
1279 }
1280 #endif /* USE_RAWKEY */
1281