xref: /openbsd/sbin/isakmpd/ike_auth.c (revision 78b63d65)
1 /*	$OpenBSD: ike_auth.c,v 1.60 2001/08/23 19:32:46 niklas 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 
791       /* We need to convert 'void *rawkey' into 'RSA *key'.  */
792       if (dns_RSA_dns_to_x509 (rawkey, rawkeylen, &key) == 0)
793 	found++;
794       else
795 	log_print ("rsa_sig_decode_hash: KEY to RSA key conversion failed");
796 
797       if (rawkey)
798 	free (rawkey);
799     }
800 #endif /* USE_DNSSEC */
801 
802 #if defined (USE_RAWKEY)
803   /* If we still have not found a key, try to read it from a file. */
804   if (!found)
805     if (get_raw_key_from_file (IKE_AUTH_RSA_SIG, id, id_len, &key) != -1)
806       found++;
807 #endif
808 
809   if (!found)
810     {
811       log_print ("rsa_sig_decode_hash: no public key found");
812       return -1;
813     }
814 
815   p = TAILQ_FIRST (&msg->payload[ISAKMP_PAYLOAD_SIG]);
816   if (!p)
817     {
818       log_print ("rsa_sig_decode_hash: missing signature payload");
819       LC (RSA_free, (key));
820       return -1;
821     }
822 
823   /* Check that the sig is of the correct size.  */
824   len = GET_ISAKMP_GEN_LENGTH (p->p) - ISAKMP_SIG_SZ;
825   if (len != LC (RSA_size, (key)))
826     {
827       LC (RSA_free, (key));
828       log_print ("rsa_sig_decode_hash: "
829 		 "SIG payload length does not match public key");
830       return -1;
831     }
832 
833   *hash_p = malloc (len);
834   if (!*hash_p)
835     {
836       LC (RSA_free, (key));
837       log_error ("rsa_sig_decode_hash: malloc (%d) failed", len);
838       return -1;
839     }
840 
841   len = LC (RSA_public_decrypt, (len, p->p + ISAKMP_SIG_DATA_OFF, *hash_p, key,
842 				 RSA_PKCS1_PADDING));
843   if (len == -1)
844     {
845       LC (RSA_free, (key));
846       log_print ("rsa_sig_decode_hash: RSA_public_decrypt () failed");
847       return -1;
848     }
849 
850   /* Store key for later use */
851   exchange->recv_key = key;
852   exchange->recv_keytype = ISAKMP_KEY_RSA;
853 
854   if (len != hashsize)
855     {
856       free (*hash_p);
857       *hash_p = 0;
858       log_print ("rsa_sig_decode_hash: len %d != hashsize %d", len, hashsize);
859       return -1;
860     }
861 
862   snprintf (header, 80, "rsa_sig_decode_hash: HASH_%c", initiator ? 'R' : 'I');
863   LOG_DBG_BUF ((LOG_MISC, 80, header, *hash_p, hashsize));
864 
865   p->flags |= PL_MARK;
866 
867   return 0;
868 }
869 #endif /* USE_X509 || USE_KEYNOTE */
870 
871 static int
872 pre_shared_encode_hash (struct message *msg)
873 {
874   struct exchange *exchange = msg->exchange;
875   struct ipsec_exch *ie = exchange->data;
876   size_t hashsize = ie->hash->hashsize;
877   char header[80];
878   int initiator = exchange->initiator;
879   u_int8_t *buf;
880 
881   buf = ipsec_add_hash_payload (msg, hashsize);
882   if (!buf)
883     return -1;
884 
885   if (ike_auth_hash (exchange, buf + ISAKMP_HASH_DATA_OFF) == -1)
886     return -1;
887 
888   snprintf (header, 80, "pre_shared_encode_hash: HASH_%c",
889 	    initiator ? 'I' : 'R');
890   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_HASH_DATA_OFF, hashsize));
891   return 0;
892 }
893 
894 #if defined (USE_X509) || defined (USE_KEYNOTE)
895 /* Encrypt the HASH into a SIG type.  */
896 static int
897 rsa_sig_encode_hash (struct message *msg)
898 {
899   struct exchange *exchange = msg->exchange;
900   struct ipsec_exch *ie = exchange->data;
901   size_t hashsize = ie->hash->hashsize;
902   struct cert_handler *handler;
903   char header[80];
904   int initiator = exchange->initiator;
905   u_int8_t *buf, *data, *buf2;
906   u_int32_t datalen;
907   u_int8_t *id;
908   size_t id_len;
909   int idtype;
910 
911   id = initiator ? exchange->id_i : exchange->id_r;
912   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
913 
914   /* We may have been provided these by the kernel */
915   buf = conf_get_str (exchange->name, "Credentials");
916   if (buf
917       && (idtype = conf_get_num (exchange->name, "Credential_Type", -1) != -1))
918     {
919       exchange->sent_certtype = idtype;
920       handler = cert_get (idtype);
921       if (!handler)
922 	{
923 	  log_print ("rsa_sig_encode_hash: cert_get (%d) failed", idtype);
924 	  return -1;
925 	}
926 
927       exchange->sent_cert = handler->cert_from_printable (buf);
928       if (!exchange->sent_cert)
929 	{
930 	  log_print ("rsa_sig_encode_hash: failed to retrieve certificate");
931 	  return -1;
932 	}
933 
934       handler->cert_serialize (exchange->sent_cert, &data, &datalen);
935       if (!data)
936 	{
937 	  log_print ("rsa_sig_encode_hash: cert serialization failed");
938 	  return -1;
939 	}
940 
941       goto aftercert; /* Skip all the certificate discovery */
942     }
943 
944   /* XXX This needs to be configurable.  */
945   idtype = ISAKMP_CERTENC_KEYNOTE;
946 
947   /* Find a certificate with subjectAltName = id.  */
948   handler = cert_get (idtype);
949   if (!handler)
950     {
951       idtype = ISAKMP_CERTENC_X509_SIG;
952       handler = cert_get (idtype);
953       if (!handler)
954 	{
955 	  log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
956 	  return -1;
957 	}
958     }
959 
960   if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
961     {
962       if (idtype == ISAKMP_CERTENC_KEYNOTE)
963 	{
964 	  idtype = ISAKMP_CERTENC_X509_SIG;
965 	  handler = cert_get (idtype);
966 	  if (!handler)
967 	    {
968 	      log_print ("rsa_sig_encode_hash: cert_get(%d) failed", idtype);
969 	      return -1;
970 	    }
971 
972 	  if (handler->cert_obtain (id, id_len, 0, &data, &datalen) == 0)
973 	    {
974 	      LOG_DBG ((LOG_MISC, 10,
975 			"rsa_sig_encode_hash: no certificate to send"));
976 	      goto skipcert;
977 	    }
978 	}
979       else
980 	{
981 	  LOG_DBG ((LOG_MISC, 10,
982 		    "rsa_sig_encode_hash: no certificate to send"));
983 	  goto skipcert;
984 	}
985     }
986 
987   /* Let's store the certificate we are going to use */
988   exchange->sent_certtype = idtype;
989   exchange->sent_cert = handler->cert_get (data, datalen);
990   if (!exchange->sent_cert)
991     {
992       free (data);
993       log_print ("rsa_sig_encode_hash: failed to get certificate from wire "
994 		 "encoding");
995       return -1;
996     }
997 
998  aftercert:
999 
1000   buf = realloc (data, ISAKMP_CERT_SZ + datalen);
1001   if (!buf)
1002     {
1003       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1004 		 ISAKMP_CERT_SZ + datalen);
1005       free (data);
1006       return -1;
1007     }
1008   memmove (buf + ISAKMP_CERT_SZ, buf, datalen);
1009   SET_ISAKMP_CERT_ENCODING (buf, idtype);
1010   if (message_add_payload (msg, ISAKMP_PAYLOAD_CERT, buf,
1011 			   ISAKMP_CERT_SZ + datalen, 1))
1012     {
1013       free (buf);
1014       return -1;
1015     }
1016 
1017  skipcert:
1018 
1019   switch (id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ])
1020     {
1021     case IPSEC_ID_IPV4_ADDR:
1022     case IPSEC_ID_IPV6_ADDR:
1023       util_ntoa ((char **)&buf2,
1024 		 id[ISAKMP_ID_TYPE_OFF - ISAKMP_GEN_SZ] == IPSEC_ID_IPV4_ADDR
1025 		 ? AF_INET : AF_INET6,
1026 		 id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ);
1027       if (!buf2)
1028 	return 0;
1029       break;
1030 
1031     case IPSEC_ID_FQDN:
1032     case IPSEC_ID_USER_FQDN:
1033       buf2 = calloc (id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1,
1034 		     sizeof (char));
1035       if (!buf2)
1036         {
1037 	  log_print ("rsa_sig_encode_hash: malloc (%d) failed",
1038 		     id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ + 1);
1039 	  return 0;
1040 	}
1041       memcpy (buf2, id + ISAKMP_ID_DATA_OFF - ISAKMP_GEN_SZ,
1042 	      id_len - ISAKMP_ID_DATA_OFF + ISAKMP_GEN_SZ);
1043       break;
1044 
1045       /* XXX Support more ID types?  */
1046     default:
1047       buf2 = 0;
1048       break;
1049     }
1050 
1051   /* Again, we may have these from the kernel */
1052   buf = conf_get_str (exchange->name, "OKAuthentication");
1053   if (buf)
1054     {
1055       key_from_printable (ISAKMP_KEY_RSA, ISAKMP_KEYTYPE_PRIVATE, buf, &data,
1056 			  &datalen);
1057       if (!data || datalen == -1)
1058 	{
1059 	  log_print ("rsa_sig_encode_hash: badly formatted RSA private key");
1060 	  return 0;
1061 	}
1062 
1063       exchange->sent_keytype = ISAKMP_KEY_RSA;
1064       exchange->sent_key = key_internalize (ISAKMP_KEY_RSA,
1065 					    ISAKMP_KEYTYPE_PRIVATE, data,
1066 					    datalen);
1067       if (!exchange->sent_key)
1068 	{
1069 	  log_print ("rsa_sig_encode_hash: bad RSA private key from dynamic "
1070 		     "SA acquisition subsystem");
1071 	  return 0;
1072 	}
1073     }
1074   else /* Try through the regular means.  */
1075     {
1076       exchange->sent_key = ike_auth_get_key (IKE_AUTH_RSA_SIG, exchange->name,
1077 					     buf2, 0);
1078       free (buf2);
1079 
1080       /* Did we find a key?  */
1081       if (!exchange->sent_key)
1082 	{
1083 	  log_print ("rsa_sig_encode_hash: could not get private key");
1084 	  return -1;
1085 	}
1086 
1087       exchange->sent_keytype = ISAKMP_KEY_RSA;
1088     }
1089 
1090   /* XXX hashsize is not necessarily prf->blocksize.  */
1091   buf = malloc (hashsize);
1092   if (!buf)
1093     {
1094       log_error ("rsa_sig_encode_hash: malloc (%d) failed", hashsize);
1095       return -1;
1096     }
1097 
1098   if (ike_auth_hash (exchange, buf) == -1)
1099     {
1100       free (buf);
1101       return -1;
1102     }
1103 
1104   snprintf (header, 80, "rsa_sig_encode_hash: HASH_%c", initiator ? 'I' : 'R');
1105   LOG_DBG_BUF ((LOG_MISC, 80, header, buf, hashsize));
1106 
1107   data = malloc (LC (RSA_size, (exchange->sent_key)));
1108   if (!data)
1109     {
1110       log_error ("rsa_sig_encode_hash: malloc (%d) failed",
1111 		 LC (RSA_size, (exchange->sent_key)));
1112       return -1;
1113     }
1114 
1115   datalen = LC (RSA_private_encrypt, (hashsize, buf, data,
1116 				      exchange->sent_key, RSA_PKCS1_PADDING));
1117   if (datalen == -1)
1118     {
1119       log_print ("rsa_sig_encode_hash: RSA_private_encrypt () failed");
1120       free (buf);
1121       return -1;
1122     }
1123 
1124   free (buf);
1125 
1126   buf = realloc (data, ISAKMP_SIG_SZ + datalen);
1127   if (!buf)
1128     {
1129       log_error ("rsa_sig_encode_hash: realloc (%p, %d) failed", data,
1130 		 ISAKMP_SIG_SZ + datalen);
1131       free (data);
1132       return -1;
1133     }
1134   memmove (buf + ISAKMP_SIG_SZ, buf, datalen);
1135 
1136   snprintf (header, 80, "rsa_sig_encode_hash: SIG_%c", initiator ? 'I' : 'R');
1137   LOG_DBG_BUF ((LOG_MISC, 80, header, buf + ISAKMP_SIG_DATA_OFF, datalen));
1138   if (message_add_payload (msg, ISAKMP_PAYLOAD_SIG, buf,
1139 			   ISAKMP_SIG_SZ + datalen, 1))
1140     {
1141       free (buf);
1142       return -1;
1143     }
1144   return 0;
1145 }
1146 #endif /* USE_X509 || USE_KEYNOTE */
1147 
1148 int
1149 ike_auth_hash (struct exchange *exchange, u_int8_t *buf)
1150 {
1151   struct ipsec_exch *ie = exchange->data;
1152   struct prf *prf;
1153   struct hash *hash = ie->hash;
1154   int initiator = exchange->initiator;
1155   u_int8_t *id;
1156   size_t id_len;
1157 
1158   /* Choose the right fields to fill-in.  */
1159   id = initiator ? exchange->id_i : exchange->id_r;
1160   id_len = initiator ? exchange->id_i_len : exchange->id_r_len;
1161 
1162   /* Allocate the prf and start calculating our HASH.  */
1163   prf = prf_alloc (ie->prf_type, hash->type, ie->skeyid, ie->skeyid_len);
1164   if (!prf)
1165     return -1;
1166 
1167   prf->Init (prf->prfctx);
1168   prf->Update (prf->prfctx, initiator ? ie->g_xi : ie->g_xr, ie->g_x_len);
1169   prf->Update (prf->prfctx, initiator ? ie->g_xr : ie->g_xi, ie->g_x_len);
1170   prf->Update (prf->prfctx,
1171 	       exchange->cookies
1172 	       + (initiator ? ISAKMP_HDR_ICOOKIE_OFF : ISAKMP_HDR_RCOOKIE_OFF),
1173 	       ISAKMP_HDR_ICOOKIE_LEN);
1174   prf->Update (prf->prfctx,
1175 	       exchange->cookies
1176 	       + (initiator ? ISAKMP_HDR_RCOOKIE_OFF : ISAKMP_HDR_ICOOKIE_OFF),
1177 	       ISAKMP_HDR_ICOOKIE_LEN);
1178   prf->Update (prf->prfctx, ie->sa_i_b, ie->sa_i_b_len);
1179   prf->Update (prf->prfctx, id, id_len);
1180   prf->Final (buf, prf->prfctx);
1181   prf_free (prf);
1182 
1183   return 0;
1184 }
1185 
1186 #if defined (USE_RAWKEY)
1187 static int
1188 get_raw_key_from_file (int type, u_int8_t *id, size_t id_len, RSA **rsa)
1189 {
1190   char filename[FILENAME_MAX];
1191   char *fstr;
1192   struct stat st;
1193   BIO *bio;
1194 
1195   if (type != IKE_AUTH_RSA_SIG) /* XXX More types? */
1196     {
1197       LOG_DBG ((LOG_NEGOTIATION, 20, "get_raw_key_from_file: "
1198 		"invalid auth type %d\n", type));
1199       return -1;
1200     }
1201 
1202   *rsa = 0;
1203 
1204   fstr = conf_get_str ("General", "Pubkey-directory");
1205   if (!fstr)
1206     fstr = PUBKEY_DIR_DEFAULT;
1207 
1208   if (snprintf (filename, sizeof filename, "%s/", fstr) > sizeof filename - 1)
1209     return -1;
1210 
1211   fstr = ipsec_id_string (id, id_len);
1212   if (!fstr)
1213     {
1214       LOG_DBG ((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1215 		"ipsec_id_string failed"));
1216       return -1;
1217     }
1218   strncat (filename, fstr, sizeof filename - 1 - strlen (filename));
1219   free (fstr);
1220 
1221   /* If the file does not exist, fail silently.  */
1222   if (stat (filename, &st) == 0)
1223     {
1224       bio = LC (BIO_new, (LC (BIO_s_file, ())));
1225       if (!bio)
1226 	{
1227 	  log_error ("get_raw_key_from_file: could not initialize BIO");
1228 	  return -1;
1229 	}
1230       if (LC (BIO_read_filename, (bio, filename)) <= 0)
1231 	{
1232 	  LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: "
1233 		   "BIO_read_filename(bio, \"%s\") failed", filename));
1234 	  LC (BIO_free, (bio));
1235 	  return -1;
1236 	}
1237       LOG_DBG((LOG_NEGOTIATION, 80, "get_raw_key_from_file: reading file %s",
1238 	       filename));
1239       *rsa = LC (PEM_read_bio_RSA_PUBKEY, (bio, NULL, NULL, NULL));
1240       LC (BIO_free, (bio));
1241     }
1242   else
1243     LOG_DBG((LOG_NEGOTIATION, 50, "get_raw_key_from_file: file %s not found",
1244 	     filename));
1245 
1246   return (*rsa ? 0 : -1);
1247 }
1248 #endif /* USE_RAWKEY */
1249