bug fix: check existence of encryption key before sending encrypted notification
[strongswan.git] / src / pluto / ipsec_doi.c
1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 *
15 * RCSID $Id: ipsec_doi.c,v 1.39 2006/04/22 21:59:20 as Exp $
16 */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <resolv.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29 #include <sys/time.h> /* for gettimeofday */
30
31 #include <freeswan.h>
32 #include <ipsec_policy.h>
33
34 #include "constants.h"
35 #include "defs.h"
36 #include "mp_defs.h"
37 #include "state.h"
38 #include "id.h"
39 #include "x509.h"
40 #include "crl.h"
41 #include "ca.h"
42 #include "certs.h"
43 #include "smartcard.h"
44 #include "connections.h"
45 #include "keys.h"
46 #include "packet.h"
47 #include "demux.h" /* needs packet.h */
48 #include "adns.h" /* needs <resolv.h> */
49 #include "dnskey.h" /* needs keys.h and adns.h */
50 #include "kernel.h"
51 #include "log.h"
52 #include "cookie.h"
53 #include "server.h"
54 #include "spdb.h"
55 #include "timer.h"
56 #include "rnd.h"
57 #include "ipsec_doi.h" /* needs demux.h and state.h */
58 #include "whack.h"
59 #include "fetch.h"
60 #include "pkcs7.h"
61 #include "asn1.h"
62
63 #include "sha1.h"
64 #include "md5.h"
65 #include "crypto.h" /* requires sha1.h and md5.h */
66 #include "vendor.h"
67 #include "alg_info.h"
68 #include "ike_alg.h"
69 #include "kernel_alg.h"
70 #include "nat_traversal.h"
71 #include "virtual.h"
72
73 /*
74 * are we sending Pluto's Vendor ID?
75 */
76 #ifdef VENDORID
77 #define SEND_PLUTO_VID 1
78 #else /* !VENDORID */
79 #define SEND_PLUTO_VID 0
80 #endif /* !VENDORID */
81
82 /*
83 * are we sending a Cisco Unity VID?
84 */
85 #ifdef CISCO_QUIRKS
86 #define SEND_CISCO_UNITY_VID 1
87 #else /* !CISCO_QUIRKS */
88 #define SEND_CISCO_UNITY_VID 0
89 #endif /* !CISCO_QUIRKS */
90
91 /* MAGIC: perform f, a function that returns notification_t
92 * and return from the ENCLOSING stf_status returning function if it fails.
93 */
94 #define RETURN_STF_FAILURE(f) \
95 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
96
97 /* create output HDR as replica of input HDR */
98 void
99 echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
100 {
101 struct isakmp_hdr r_hdr = md->hdr; /* mostly same as incoming header */
102
103 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
104 if (enc)
105 r_hdr.isa_flags |= ISAKMP_FLAG_ENCRYPTION;
106 /* some day, we may have to set r_hdr.isa_version */
107 r_hdr.isa_np = np;
108 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
109 impossible(); /* surely must have room and be well-formed */
110 }
111
112 /* Compute DH shared secret from our local secret and the peer's public value.
113 * We make the leap that the length should be that of the group
114 * (see quoted passage at start of ACCEPT_KE).
115 */
116 static void
117 compute_dh_shared(struct state *st, const chunk_t g
118 , const struct oakley_group_desc *group)
119 {
120 MP_INT mp_g, mp_shared;
121 struct timeval tv0, tv1;
122 unsigned long tv_diff;
123
124 gettimeofday(&tv0, NULL);
125 passert(st->st_sec_in_use);
126 n_to_mpz(&mp_g, g.ptr, g.len);
127 mpz_init(&mp_shared);
128 mpz_powm(&mp_shared, &mp_g, &st->st_sec, group->modulus);
129 mpz_clear(&mp_g);
130 freeanychunk(st->st_shared); /* happens in odd error cases */
131 st->st_shared = mpz_to_n(&mp_shared, group->bytes);
132 mpz_clear(&mp_shared);
133 gettimeofday(&tv1, NULL);
134 tv_diff=(tv1.tv_sec - tv0.tv_sec) * 1000000 + (tv1.tv_usec - tv0.tv_usec);
135 DBG(DBG_CRYPT,
136 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
137 , enum_show(&oakley_group_names, st->st_oakley.group->group)
138 , tv_diff);
139 );
140 /* if took more than 200 msec ... */
141 if (tv_diff > 200000) {
142 loglog(RC_LOG_SERIOUS, "WARNING: compute_dh_shared(): for %s took "
143 "%ld usec"
144 , enum_show(&oakley_group_names, st->st_oakley.group->group)
145 , tv_diff);
146 }
147
148 DBG_cond_dump_chunk(DBG_CRYPT, "DH shared secret:\n", st->st_shared);
149 }
150
151 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
152 * the corresponding public value (g). This is emitted as a KE payload.
153 */
154 static bool
155 build_and_ship_KE(struct state *st, chunk_t *g
156 , const struct oakley_group_desc *group, pb_stream *outs, u_int8_t np)
157 {
158 if (!st->st_sec_in_use)
159 {
160 u_char tmp[LOCALSECRETSIZE];
161 MP_INT mp_g;
162
163 get_rnd_bytes(tmp, LOCALSECRETSIZE);
164 st->st_sec_in_use = TRUE;
165 n_to_mpz(&st->st_sec, tmp, LOCALSECRETSIZE);
166
167 mpz_init(&mp_g);
168 mpz_powm(&mp_g, &groupgenerator, &st->st_sec, group->modulus);
169 freeanychunk(*g); /* happens in odd error cases */
170 *g = mpz_to_n(&mp_g, group->bytes);
171 mpz_clear(&mp_g);
172 DBG(DBG_CRYPT,
173 DBG_dump("Local DH secret:\n", tmp, LOCALSECRETSIZE);
174 DBG_dump_chunk("Public DH value sent:\n", *g));
175 }
176 return out_generic_chunk(np, &isakmp_keyex_desc, outs, *g, "keyex value");
177 }
178
179 /* accept_ke
180 *
181 * Check and accept DH public value (Gi or Gr) from peer's message.
182 * According to RFC2409 "The Internet key exchange (IKE)" 5:
183 * The Diffie-Hellman public value passed in a KE payload, in either
184 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
185 * Diffie-Hellman group enforced, if necessary, by pre-pending the
186 * value with zeros.
187 */
188 static notification_t
189 accept_KE(chunk_t *dest, const char *val_name
190 , const struct oakley_group_desc *gr
191 , pb_stream *pbs)
192 {
193 if (pbs_left(pbs) != gr->bytes)
194 {
195 loglog(RC_LOG_SERIOUS, "KE has %u byte DH public value; %u required"
196 , (unsigned) pbs_left(pbs), (unsigned) gr->bytes);
197 /* XXX Could send notification back */
198 return INVALID_KEY_INFORMATION;
199 }
200 clonereplacechunk(*dest, pbs->cur, pbs_left(pbs), val_name);
201 DBG_cond_dump_chunk(DBG_CRYPT, "DH public value received:\n", *dest);
202 return NOTHING_WRONG;
203 }
204
205 /* accept_PFS_KE
206 *
207 * Check and accept optional Quick Mode KE payload for PFS.
208 * Extends ACCEPT_PFS to check whether KE is allowed or required.
209 */
210 static notification_t
211 accept_PFS_KE(struct msg_digest *md, chunk_t *dest
212 , const char *val_name, const char *msg_name)
213 {
214 struct state *st = md->st;
215 struct payload_digest *const ke_pd = md->chain[ISAKMP_NEXT_KE];
216
217 if (ke_pd == NULL)
218 {
219 if (st->st_pfs_group != NULL)
220 {
221 loglog(RC_LOG_SERIOUS, "missing KE payload in %s message", msg_name);
222 return INVALID_KEY_INFORMATION;
223 }
224 }
225 else
226 {
227 if (st->st_pfs_group == NULL)
228 {
229 loglog(RC_LOG_SERIOUS, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
230 , msg_name);
231 return INVALID_KEY_INFORMATION;
232 }
233 if (ke_pd->next != NULL)
234 {
235 loglog(RC_LOG_SERIOUS, "%s message contains several KE payloads; we accept at most one", msg_name);
236 return INVALID_KEY_INFORMATION; /* ??? */
237 }
238 return accept_KE(dest, val_name, st->st_pfs_group, &ke_pd->pbs);
239 }
240 return NOTHING_WRONG;
241 }
242
243 static bool
244 build_and_ship_nonce(chunk_t *n, pb_stream *outs, u_int8_t np
245 , const char *name)
246 {
247 freeanychunk(*n);
248 setchunk(*n, alloc_bytes(DEFAULT_NONCE_SIZE, name), DEFAULT_NONCE_SIZE);
249 get_rnd_bytes(n->ptr, DEFAULT_NONCE_SIZE);
250 return out_generic_chunk(np, &isakmp_nonce_desc, outs, *n, name);
251 }
252
253 static bool
254 collect_rw_ca_candidates(struct msg_digest *md, generalName_t **top)
255 {
256 struct connection *d = find_host_connection(&md->iface->addr
257 , pluto_port, (ip_address*)NULL, md->sender_port, LEMPTY);
258
259 for (; d != NULL; d = d->hp_next)
260 {
261 /* must be a road warrior connection */
262 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)
263 && d->spd.that.ca.ptr != NULL)
264 {
265 generalName_t *gn;
266 bool new_entry = TRUE;
267
268 for (gn = *top; gn != NULL; gn = gn->next)
269 {
270 if (same_dn(gn->name, d->spd.that.ca))
271 {
272 new_entry = FALSE;
273 break;
274 }
275 }
276 if (new_entry)
277 {
278 gn = alloc_thing(generalName_t, "generalName");
279 gn->kind = GN_DIRECTORY_NAME;
280 gn->name = d->spd.that.ca;
281 gn->next = *top;
282 *top = gn;
283 }
284 }
285 }
286 return *top != NULL;
287 }
288
289 static bool
290 build_and_ship_CR(u_int8_t type, chunk_t ca, pb_stream *outs, u_int8_t np)
291 {
292 pb_stream cr_pbs;
293 struct isakmp_cr cr_hd;
294 cr_hd.isacr_np = np;
295 cr_hd.isacr_type = type;
296
297 /* build CR header */
298 if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, outs, &cr_pbs))
299 return FALSE;
300
301 if (ca.ptr != NULL)
302 {
303 /* build CR body containing the distinguished name of the CA */
304 if (!out_chunk(ca, &cr_pbs, "CA"))
305 return FALSE;
306 }
307 close_output_pbs(&cr_pbs);
308 return TRUE;
309 }
310
311 /* Send a notification to the peer. We could decide
312 * whether to send the notification, based on the type and the
313 * destination, if we care to.
314 */
315 static void
316 send_notification(struct state *sndst, u_int16_t type, struct state *encst,
317 msgid_t msgid, u_char *icookie, u_char *rcookie,
318 u_char *spi, size_t spisize, u_char protoid)
319 {
320 u_char buffer[1024];
321 pb_stream pbs, r_hdr_pbs;
322 u_char *r_hashval = NULL; /* where in reply to jam hash value */
323 u_char *r_hash_start = NULL; /* start of what is to be hashed */
324
325 passert((sndst) && (sndst->st_connection));
326
327 plog("sending %snotification %s to %s:%u"
328 , encst ? "encrypted " : ""
329 , enum_name(&notification_names, type)
330 , ip_str(&sndst->st_connection->spd.that.host_addr)
331 , (unsigned)sndst->st_connection->spd.that.host_port);
332
333 memset(buffer, 0, sizeof(buffer));
334 init_pbs(&pbs, buffer, sizeof(buffer), "ISAKMP notify");
335
336 /* HDR* */
337 {
338 struct isakmp_hdr hdr;
339
340 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
341 hdr.isa_np = encst ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_N;
342 hdr.isa_xchg = ISAKMP_XCHG_INFO;
343 hdr.isa_msgid = msgid;
344 hdr.isa_flags = encst ? ISAKMP_FLAG_ENCRYPTION : 0;
345 if (icookie)
346 memcpy(hdr.isa_icookie, icookie, COOKIE_SIZE);
347 if (rcookie)
348 memcpy(hdr.isa_rcookie, rcookie, COOKIE_SIZE);
349 if (!out_struct(&hdr, &isakmp_hdr_desc, &pbs, &r_hdr_pbs))
350 impossible();
351 }
352
353 /* HASH -- value to be filled later */
354 if (encst)
355 {
356 pb_stream hash_pbs;
357 if (!out_generic(ISAKMP_NEXT_N, &isakmp_hash_desc, &r_hdr_pbs,
358 &hash_pbs))
359 impossible();
360 r_hashval = hash_pbs.cur; /* remember where to plant value */
361 if (!out_zero(
362 encst->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH"))
363 impossible();
364 close_output_pbs(&hash_pbs);
365 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH */
366 }
367
368 /* Notification Payload */
369 {
370 pb_stream not_pbs;
371 struct isakmp_notification isan;
372
373 isan.isan_doi = ISAKMP_DOI_IPSEC;
374 isan.isan_np = ISAKMP_NEXT_NONE;
375 isan.isan_type = type;
376 isan.isan_spisize = spisize;
377 isan.isan_protoid = protoid;
378
379 if (!out_struct(&isan, &isakmp_notification_desc, &r_hdr_pbs, &not_pbs)
380 || !out_raw(spi, spisize, &not_pbs, "spi"))
381 impossible();
382 close_output_pbs(&not_pbs);
383 }
384
385 /* calculate hash value and patch into Hash Payload */
386 if (encst)
387 {
388 struct hmac_ctx ctx;
389 hmac_init_chunk(&ctx, encst->st_oakley.hasher, encst->st_skeyid_a);
390 hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
391 hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
392 hmac_final(r_hashval, &ctx);
393
394 DBG(DBG_CRYPT,
395 DBG_log("HASH computed:");
396 DBG_dump("", r_hashval, ctx.hmac_digest_size);
397 )
398 }
399
400 /* Encrypt message (preserve st_iv and st_new_iv) */
401 if (encst)
402 {
403 u_char old_iv[MAX_DIGEST_LEN];
404 u_char new_iv[MAX_DIGEST_LEN];
405
406 u_int old_iv_len = encst->st_iv_len;
407 u_int new_iv_len = encst->st_new_iv_len;
408
409 if (old_iv_len > MAX_DIGEST_LEN || new_iv_len > MAX_DIGEST_LEN)
410 impossible();
411
412 memcpy(old_iv, encst->st_iv, old_iv_len);
413 memcpy(new_iv, encst->st_new_iv, new_iv_len);
414
415 if (!IS_ISAKMP_SA_ESTABLISHED(encst->st_state))
416 {
417 memcpy(encst->st_ph1_iv, encst->st_new_iv, encst->st_new_iv_len);
418 encst->st_ph1_iv_len = encst->st_new_iv_len;
419 }
420 init_phase2_iv(encst, &msgid);
421 if (!encrypt_message(&r_hdr_pbs, encst))
422 impossible();
423
424 /* restore preserved st_iv and st_new_iv */
425 memcpy(encst->st_iv, old_iv, old_iv_len);
426 memcpy(encst->st_new_iv, new_iv, new_iv_len);
427 encst->st_iv_len = old_iv_len;
428 encst->st_new_iv_len = new_iv_len;
429 }
430 else
431 {
432 close_output_pbs(&r_hdr_pbs);
433 }
434
435 /* Send packet (preserve st_tpacket) */
436 {
437 chunk_t saved_tpacket = sndst->st_tpacket;
438
439 setchunk(sndst->st_tpacket, pbs.start, pbs_offset(&pbs));
440 send_packet(sndst, "ISAKMP notify");
441 sndst->st_tpacket = saved_tpacket;
442 }
443 }
444
445 void
446 send_notification_from_state(struct state *st, enum state_kind state,
447 u_int16_t type)
448 {
449 struct state *p1st;
450
451 passert(st);
452
453 if (state == STATE_UNDEFINED)
454 state = st->st_state;
455
456 if (IS_QUICK(state))
457 {
458 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
459 if ((p1st == NULL) || (!IS_ISAKMP_SA_ESTABLISHED(p1st->st_state)))
460 {
461 loglog(RC_LOG_SERIOUS,
462 "no Phase1 state for Quick mode notification");
463 return;
464 }
465 send_notification(st, type, p1st, generate_msgid(p1st),
466 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
467 }
468 else if (IS_ISAKMP_ENCRYPTED(state) && st->st_enc_key.ptr != NULL)
469 {
470 send_notification(st, type, st, generate_msgid(st),
471 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
472 }
473 else
474 {
475 /* no ISAKMP SA established - don't encrypt notification */
476 send_notification(st, type, NULL, 0,
477 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
478 }
479 }
480
481 void
482 send_notification_from_md(struct msg_digest *md, u_int16_t type)
483 {
484 /**
485 * Create a dummy state to be able to use send_packet in
486 * send_notification
487 *
488 * we need to set:
489 * st_connection->that.host_addr
490 * st_connection->that.host_port
491 * st_connection->interface
492 */
493 struct state st;
494 struct connection cnx;
495
496 passert(md);
497
498 memset(&st, 0, sizeof(st));
499 memset(&cnx, 0, sizeof(cnx));
500 st.st_connection = &cnx;
501 cnx.spd.that.host_addr = md->sender;
502 cnx.spd.that.host_port = md->sender_port;
503 cnx.interface = md->iface;
504
505 send_notification(&st, type, NULL, 0,
506 md->hdr.isa_icookie, md->hdr.isa_rcookie, NULL, 0, PROTO_ISAKMP);
507 }
508
509 /* Send a Delete Notification to announce deletion of ISAKMP SA or
510 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
511 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
512 */
513 void
514 send_delete(struct state *st)
515 {
516 pb_stream reply_pbs;
517 pb_stream r_hdr_pbs;
518 msgid_t msgid;
519 u_char buffer[8192];
520 struct state *p1st;
521 ip_said said[EM_MAXRELSPIS];
522 ip_said *ns = said;
523 u_char
524 *r_hashval, /* where in reply to jam hash value */
525 *r_hash_start; /* start of what is to be hashed */
526 bool isakmp_sa = FALSE;
527
528 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
529 {
530 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
531 if (p1st == NULL)
532 {
533 DBG(DBG_CONTROL, DBG_log("no Phase 1 state for Delete"));
534 return;
535 }
536
537 if (st->st_ah.present)
538 {
539 ns->spi = st->st_ah.our_spi;
540 ns->dst = st->st_connection->spd.this.host_addr;
541 ns->proto = PROTO_IPSEC_AH;
542 ns++;
543 }
544 if (st->st_esp.present)
545 {
546 ns->spi = st->st_esp.our_spi;
547 ns->dst = st->st_connection->spd.this.host_addr;
548 ns->proto = PROTO_IPSEC_ESP;
549 ns++;
550 }
551
552 passert(ns != said); /* there must be some SAs to delete */
553 }
554 else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state))
555 {
556 p1st = st;
557 isakmp_sa = TRUE;
558 }
559 else
560 {
561 return; /* nothing to do */
562 }
563
564 msgid = generate_msgid(p1st);
565
566 zero(buffer);
567 init_pbs(&reply_pbs, buffer, sizeof(buffer), "delete msg");
568
569 /* HDR* */
570 {
571 struct isakmp_hdr hdr;
572
573 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
574 hdr.isa_np = ISAKMP_NEXT_HASH;
575 hdr.isa_xchg = ISAKMP_XCHG_INFO;
576 hdr.isa_msgid = msgid;
577 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
578 memcpy(hdr.isa_icookie, p1st->st_icookie, COOKIE_SIZE);
579 memcpy(hdr.isa_rcookie, p1st->st_rcookie, COOKIE_SIZE);
580 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_pbs, &r_hdr_pbs))
581 impossible();
582 }
583
584 /* HASH -- value to be filled later */
585 {
586 pb_stream hash_pbs;
587
588 if (!out_generic(ISAKMP_NEXT_D, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
589 impossible();
590 r_hashval = hash_pbs.cur; /* remember where to plant value */
591 if (!out_zero(p1st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH(1)"))
592 impossible();
593 close_output_pbs(&hash_pbs);
594 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
595 }
596
597 /* Delete Payloads */
598 if (isakmp_sa)
599 {
600 pb_stream del_pbs;
601 struct isakmp_delete isad;
602 u_char isakmp_spi[2*COOKIE_SIZE];
603
604 isad.isad_doi = ISAKMP_DOI_IPSEC;
605 isad.isad_np = ISAKMP_NEXT_NONE;
606 isad.isad_spisize = (2 * COOKIE_SIZE);
607 isad.isad_protoid = PROTO_ISAKMP;
608 isad.isad_nospi = 1;
609
610 memcpy(isakmp_spi, st->st_icookie, COOKIE_SIZE);
611 memcpy(isakmp_spi+COOKIE_SIZE, st->st_rcookie, COOKIE_SIZE);
612
613 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
614 || !out_raw(&isakmp_spi, (2*COOKIE_SIZE), &del_pbs, "delete payload"))
615 impossible();
616 close_output_pbs(&del_pbs);
617 }
618 else
619 {
620 while (ns != said)
621 {
622
623 pb_stream del_pbs;
624 struct isakmp_delete isad;
625
626 ns--;
627 isad.isad_doi = ISAKMP_DOI_IPSEC;
628 isad.isad_np = ns == said? ISAKMP_NEXT_NONE : ISAKMP_NEXT_D;
629 isad.isad_spisize = sizeof(ipsec_spi_t);
630 isad.isad_protoid = ns->proto;
631
632 isad.isad_nospi = 1;
633 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
634 || !out_raw(&ns->spi, sizeof(ipsec_spi_t), &del_pbs, "delete payload"))
635 impossible();
636 close_output_pbs(&del_pbs);
637 }
638 }
639
640 /* calculate hash value and patch into Hash Payload */
641 {
642 struct hmac_ctx ctx;
643 hmac_init_chunk(&ctx, p1st->st_oakley.hasher, p1st->st_skeyid_a);
644 hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
645 hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
646 hmac_final(r_hashval, &ctx);
647
648 DBG(DBG_CRYPT,
649 DBG_log("HASH(1) computed:");
650 DBG_dump("", r_hashval, ctx.hmac_digest_size);
651 )
652 }
653
654 /* Do a dance to avoid needing a new state object.
655 * We use the Phase 1 State. This is the one with right
656 * IV, for one thing.
657 * The tricky bits are:
658 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
659 * - we need to preserve (save/restore) st_tpacket.
660 */
661 {
662 u_char old_iv[MAX_DIGEST_LEN];
663 chunk_t saved_tpacket = p1st->st_tpacket;
664
665 memcpy(old_iv, p1st->st_iv, p1st->st_iv_len);
666 init_phase2_iv(p1st, &msgid);
667
668 if (!encrypt_message(&r_hdr_pbs, p1st))
669 impossible();
670
671 setchunk(p1st->st_tpacket, reply_pbs.start, pbs_offset(&reply_pbs));
672 send_packet(p1st, "delete notify");
673 p1st->st_tpacket = saved_tpacket;
674
675 /* get back old IV for this state */
676 memcpy(p1st->st_iv, old_iv, p1st->st_iv_len);
677 }
678 }
679
680 void
681 accept_delete(struct state *st, struct msg_digest *md, struct payload_digest *p)
682 {
683 struct isakmp_delete *d = &(p->payload.delete);
684 size_t sizespi;
685 int i;
686
687 if (!md->encrypted)
688 {
689 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: not encrypted");
690 return;
691 }
692
693 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
694 {
695 /* can't happen (if msg is encrypt), but just to be sure */
696 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
697 "ISAKMP SA not established");
698 return;
699 }
700
701 if (d->isad_nospi == 0)
702 {
703 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: no SPI");
704 return;
705 }
706
707 switch (d->isad_protoid)
708 {
709 case PROTO_ISAKMP:
710 sizespi = 2 * COOKIE_SIZE;
711 break;
712 case PROTO_IPSEC_AH:
713 case PROTO_IPSEC_ESP:
714 sizespi = sizeof(ipsec_spi_t);
715 break;
716 case PROTO_IPCOMP:
717 /* nothing interesting to delete */
718 return;
719 default:
720 loglog(RC_LOG_SERIOUS
721 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
722 , enum_show(&protocol_names, d->isad_protoid));
723 return;
724 }
725
726 if (d->isad_spisize != sizespi)
727 {
728 loglog(RC_LOG_SERIOUS
729 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
730 , d->isad_spisize, enum_show(&protocol_names, d->isad_protoid));
731 return;
732 }
733
734 if (pbs_left(&p->pbs) != d->isad_nospi * sizespi)
735 {
736 loglog(RC_LOG_SERIOUS
737 , "ignoring Delete SA payload: invalid payload size");
738 return;
739 }
740
741 for (i = 0; i < d->isad_nospi; i++)
742 {
743 u_char *spi = p->pbs.cur + (i * sizespi);
744
745 if (d->isad_protoid == PROTO_ISAKMP)
746 {
747 /**
748 * ISAKMP
749 */
750 struct state *dst = find_state(spi /*iCookie*/
751 , spi+COOKIE_SIZE /*rCookie*/
752 , &st->st_connection->spd.that.host_addr
753 , MAINMODE_MSGID);
754
755 if (dst == NULL)
756 {
757 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
758 "ISAKMP SA not found (maybe expired)");
759 }
760 else if (!same_peer_ids(st->st_connection, dst->st_connection, NULL))
761 {
762 /* we've not authenticated the relevant identities */
763 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
764 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
765 }
766 else
767 {
768 struct connection *oldc;
769
770 oldc = cur_connection;
771 set_cur_connection(dst->st_connection);
772
773 if (nat_traversal_enabled)
774 nat_traversal_change_port_lookup(md, dst);
775
776 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
777 "deleting ISAKMP State #%lu", dst->st_serialno);
778 delete_state(dst);
779 set_cur_connection(oldc);
780 }
781 }
782 else
783 {
784 /**
785 * IPSEC (ESP/AH)
786 */
787 bool bogus;
788 struct state *dst = find_phase2_state_to_delete(st
789 , d->isad_protoid
790 , *(ipsec_spi_t *)spi /* network order */
791 , &bogus);
792
793 if (dst == NULL)
794 {
795 loglog(RC_LOG_SERIOUS
796 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
797 , enum_show(&protocol_names, d->isad_protoid)
798 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
799 , bogus ? "our SPI - bogus implementation" : "maybe expired");
800 }
801 else
802 {
803 struct connection *rc = dst->st_connection;
804 struct connection *oldc;
805
806 oldc = cur_connection;
807 set_cur_connection(rc);
808
809 if (nat_traversal_enabled)
810 nat_traversal_change_port_lookup(md, dst);
811
812 if (rc->newest_ipsec_sa == dst->st_serialno
813 && (rc->policy & POLICY_UP))
814 {
815 /* Last IPSec SA for a permanent connection that we
816 * have initiated. Replace it in a few seconds.
817 *
818 * Useful if the other peer is rebooting.
819 */
820 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
821 if (dst->st_event != NULL
822 && dst->st_event->ev_type == EVENT_SA_REPLACE
823 && dst->st_event->ev_time <= DELETE_SA_DELAY + now())
824 {
825 /* Patch from Angus Lees to ignore retransmited
826 * Delete SA.
827 */
828 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
829 "already replacing IPSEC State #%lu in %d seconds"
830 , dst->st_serialno, (int)(dst->st_event->ev_time - now()));
831 }
832 else
833 {
834 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
835 "replace IPSEC State #%lu in %d seconds"
836 , dst->st_serialno, DELETE_SA_DELAY);
837 dst->st_margin = DELETE_SA_DELAY;
838 delete_event(dst);
839 event_schedule(EVENT_SA_REPLACE, DELETE_SA_DELAY, dst);
840 }
841 }
842 else
843 {
844 loglog(RC_LOG_SERIOUS, "received Delete SA(0x%08lx) payload: "
845 "deleting IPSEC State #%lu"
846 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
847 , dst->st_serialno);
848 delete_state(dst);
849 }
850
851 /* reset connection */
852 set_cur_connection(oldc);
853 }
854 }
855 }
856 }
857
858 /* The whole message must be a multiple of 4 octets.
859 * I'm not sure where this is spelled out, but look at
860 * rfc2408 3.6 Transform Payload.
861 * Note: it talks about 4 BYTE boundaries!
862 */
863 void
864 close_message(pb_stream *pbs)
865 {
866 size_t padding = pad_up(pbs_offset(pbs), 4);
867
868 if (padding != 0)
869 (void) out_zero(padding, pbs, "message padding");
870 close_output_pbs(pbs);
871 }
872
873 /* Initiate an Oakley Main Mode exchange.
874 * --> HDR;SA
875 * Note: this is not called from demux.c
876 */
877 static stf_status
878 main_outI1(int whack_sock, struct connection *c, struct state *predecessor
879 , lset_t policy, unsigned long try)
880 {
881 struct state *st = new_state();
882 pb_stream reply; /* not actually a reply, but you know what I mean */
883 pb_stream rbody;
884
885 int vids_to_send = 0;
886
887 /* set up new state */
888 st->st_connection = c;
889 set_cur_state(st); /* we must reset before exit */
890 st->st_policy = policy & ~POLICY_IPSEC_MASK;
891 st->st_whack_sock = whack_sock;
892 st->st_try = try;
893 st->st_state = STATE_MAIN_I1;
894
895 /* determine how many Vendor ID payloads we will be sending */
896 if (SEND_PLUTO_VID)
897 vids_to_send++;
898 if (SEND_CISCO_UNITY_VID)
899 vids_to_send++;
900 if (c->spd.this.cert.type == CERT_PGP)
901 vids_to_send++;
902 /* always send XAUTH Vendor ID */
903 vids_to_send++;
904 /* always send DPD Vendor ID */
905 vids_to_send++;
906 if (nat_traversal_enabled)
907 vids_to_send++;
908
909 get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr);
910
911 insert_state(st); /* needs cookies, connection, and msgid (0) */
912
913 if (HAS_IPSEC_POLICY(policy))
914 add_pending(dup_any(whack_sock), st, c, policy, 1
915 , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
916
917 if (predecessor == NULL)
918 plog("initiating Main Mode");
919 else
920 plog("initiating Main Mode to replace #%lu", predecessor->st_serialno);
921
922 /* set up reply */
923 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
924
925 /* HDR out */
926 {
927 struct isakmp_hdr hdr;
928
929 zero(&hdr); /* default to 0 */
930 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
931 hdr.isa_np = ISAKMP_NEXT_SA;
932 hdr.isa_xchg = ISAKMP_XCHG_IDPROT;
933 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
934 /* R-cookie, flags and MessageID are left zero */
935
936 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
937 {
938 reset_cur_state();
939 return STF_INTERNAL_ERROR;
940 }
941 }
942
943 /* SA out */
944 {
945 u_char *sa_start = rbody.cur;
946 lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
947
948 if (!out_sa(&rbody, &oakley_sadb, st, TRUE
949 , vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE))
950 {
951 reset_cur_state();
952 return STF_INTERNAL_ERROR;
953 }
954
955 /* save initiator SA for later HASH */
956 passert(st->st_p1isa.ptr == NULL); /* no leak! (MUST be first time) */
957 clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
958 , "sa in main_outI1");
959 }
960
961 /* if enabled send Pluto Vendor ID */
962 if (SEND_PLUTO_VID)
963 {
964 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
965 , &rbody, VID_STRONGSWAN))
966 {
967 reset_cur_state();
968 return STF_INTERNAL_ERROR;
969 }
970 }
971
972 /* if enabled send Cisco Unity Vendor ID */
973 if (SEND_CISCO_UNITY_VID)
974 {
975 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
976 , &rbody, VID_CISCO_UNITY))
977 {
978 reset_cur_state();
979 return STF_INTERNAL_ERROR;
980 }
981 }
982 /* if we have an OpenPGP certificate we assume an
983 * OpenPGP peer and have to send the Vendor ID
984 */
985 if (c->spd.this.cert.type == CERT_PGP)
986 {
987 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
988 , &rbody, VID_OPENPGP))
989 {
990 reset_cur_state();
991 return STF_INTERNAL_ERROR;
992 }
993 }
994
995 /* Announce our ability to do eXtended AUTHentication to the peer */
996 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
997 , &rbody, VID_MISC_XAUTH))
998 {
999 reset_cur_state();
1000 return STF_INTERNAL_ERROR;
1001 }
1002
1003 /* Announce our ability to do Dead Peer Detection to the peer */
1004 {
1005 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1006 , &rbody, VID_MISC_DPD))
1007 {
1008 reset_cur_state();
1009 return STF_INTERNAL_ERROR;
1010 }
1011 }
1012
1013 if (nat_traversal_enabled)
1014 {
1015 /* Add supported NAT-Traversal VID */
1016 if (!nat_traversal_add_vid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1017 , &rbody))
1018 {
1019 reset_cur_state();
1020 return STF_INTERNAL_ERROR;
1021 }
1022 }
1023
1024 close_message(&rbody);
1025 close_output_pbs(&reply);
1026
1027 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
1028 , "reply packet for main_outI1");
1029
1030 /* Transmit */
1031
1032 send_packet(st, "main_outI1");
1033
1034 /* Set up a retransmission event, half a minute henceforth */
1035 delete_event(st);
1036 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1037
1038 if (predecessor != NULL)
1039 {
1040 update_pending(predecessor, st);
1041 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1042 , "%s: initiate, replacing #%lu"
1043 , enum_name(&state_names, st->st_state)
1044 , predecessor->st_serialno);
1045 }
1046 else
1047 {
1048 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1049 , "%s: initiate", enum_name(&state_names, st->st_state));
1050 }
1051 reset_cur_state();
1052 return STF_OK;
1053 }
1054
1055 void
1056 ipsecdoi_initiate(int whack_sock
1057 , struct connection *c
1058 , lset_t policy
1059 , unsigned long try
1060 , so_serial_t replacing)
1061 {
1062 /* If there's already an ISAKMP SA established, use that and
1063 * go directly to Quick Mode. We are even willing to use one
1064 * that is still being negotiated, but only if we are the Initiator
1065 * (thus we can be sure that the IDs are not going to change;
1066 * other issues around intent might matter).
1067 * Note: there is no way to initiate with a Road Warrior.
1068 */
1069 struct state *st = find_phase1_state(c
1070 , ISAKMP_SA_ESTABLISHED_STATES | PHASE1_INITIATOR_STATES);
1071
1072 if (st == NULL)
1073 {
1074 (void) main_outI1(whack_sock, c, NULL, policy, try);
1075 }
1076 else if (HAS_IPSEC_POLICY(policy))
1077 {
1078 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1079 {
1080 /* leave our Phase 2 negotiation pending */
1081 add_pending(whack_sock, st, c, policy, try, replacing);
1082 }
1083 else
1084 {
1085 /* ??? we assume that peer_nexthop_sin isn't important:
1086 * we already have it from when we negotiated the ISAKMP SA!
1087 * It isn't clear what to do with the error return.
1088 */
1089 (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1090 }
1091 }
1092 else
1093 {
1094 close_any(whack_sock);
1095 }
1096 }
1097
1098 /* Replace SA with a fresh one that is similar
1099 *
1100 * Shares some logic with ipsecdoi_initiate, but not the same!
1101 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1102 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1103 * ISAKMP SA if needed.
1104 * - duplicate whack fd, if live.
1105 * Does not delete the old state -- someone else will do that.
1106 */
1107 void
1108 ipsecdoi_replace(struct state *st, unsigned long try)
1109 {
1110 int whack_sock = dup_any(st->st_whack_sock);
1111 lset_t policy = st->st_policy;
1112
1113 if (IS_PHASE1(st->st_state))
1114 {
1115 passert(!HAS_IPSEC_POLICY(policy));
1116 (void) main_outI1(whack_sock, st->st_connection, st, policy, try);
1117 }
1118 else
1119 {
1120 /* Add features of actual old state to policy. This ensures
1121 * that rekeying doesn't downgrade security. I admit that
1122 * this doesn't capture everything.
1123 */
1124 if (st->st_pfs_group != NULL)
1125 policy |= POLICY_PFS;
1126 if (st->st_ah.present)
1127 {
1128 policy |= POLICY_AUTHENTICATE;
1129 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1130 policy |= POLICY_TUNNEL;
1131 }
1132 if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1133 {
1134 policy |= POLICY_ENCRYPT;
1135 if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1136 policy |= POLICY_TUNNEL;
1137 }
1138 if (st->st_ipcomp.present)
1139 {
1140 policy |= POLICY_COMPRESS;
1141 if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1142 policy |= POLICY_TUNNEL;
1143 }
1144 passert(HAS_IPSEC_POLICY(policy));
1145 ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1146 , st->st_serialno);
1147 }
1148 }
1149
1150 /* SKEYID for preshared keys.
1151 * See draft-ietf-ipsec-ike-01.txt 4.1
1152 */
1153 static bool
1154 skeyid_preshared(struct state *st)
1155 {
1156 const chunk_t *pss = get_preshared_secret(st->st_connection);
1157
1158 if (pss == NULL)
1159 {
1160 loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1161 return FALSE;
1162 }
1163 else
1164 {
1165 struct hmac_ctx ctx;
1166
1167 hmac_init_chunk(&ctx, st->st_oakley.hasher, *pss);
1168 hmac_update_chunk(&ctx, st->st_ni);
1169 hmac_update_chunk(&ctx, st->st_nr);
1170 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_preshared()", &ctx);
1171 return TRUE;
1172 }
1173 }
1174
1175 static bool
1176 skeyid_digisig(struct state *st)
1177 {
1178 struct hmac_ctx ctx;
1179 chunk_t nir;
1180
1181 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1182 * so we have to build a temporary concatentation.
1183 */
1184 nir.len = st->st_ni.len + st->st_nr.len;
1185 nir.ptr = alloc_bytes(nir.len, "Ni + Nr in skeyid_digisig");
1186 memcpy(nir.ptr, st->st_ni.ptr, st->st_ni.len);
1187 memcpy(nir.ptr+st->st_ni.len, st->st_nr.ptr, st->st_nr.len);
1188 hmac_init_chunk(&ctx, st->st_oakley.hasher, nir);
1189 pfree(nir.ptr);
1190
1191 hmac_update_chunk(&ctx, st->st_shared);
1192 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_digisig()", &ctx);
1193 return TRUE;
1194 }
1195
1196 /* Generate the SKEYID_* and new IV
1197 * See draft-ietf-ipsec-ike-01.txt 4.1
1198 */
1199 static bool
1200 generate_skeyids_iv(struct state *st)
1201 {
1202 /* Generate the SKEYID */
1203 switch (st->st_oakley.auth)
1204 {
1205 case OAKLEY_PRESHARED_KEY:
1206 case XAUTHInitPreShared:
1207 case XAUTHRespPreShared:
1208 if (!skeyid_preshared(st))
1209 return FALSE;
1210 break;
1211
1212 case OAKLEY_RSA_SIG:
1213 case XAUTHInitRSA:
1214 case XAUTHRespRSA:
1215 if (!skeyid_digisig(st))
1216 return FALSE;
1217 break;
1218
1219 case OAKLEY_DSS_SIG:
1220 /* XXX */
1221
1222 case OAKLEY_RSA_ENC:
1223 case OAKLEY_RSA_ENC_REV:
1224 case OAKLEY_ELGAMAL_ENC:
1225 case OAKLEY_ELGAMAL_ENC_REV:
1226 /* XXX */
1227
1228 default:
1229 bad_case(st->st_oakley.auth);
1230 }
1231
1232 /* generate SKEYID_* from SKEYID */
1233 {
1234 struct hmac_ctx ctx;
1235
1236 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1237
1238 /* SKEYID_D */
1239 hmac_update_chunk(&ctx, st->st_shared);
1240 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1241 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1242 hmac_update(&ctx, "\0", 1);
1243 hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1244
1245 /* SKEYID_A */
1246 hmac_reinit(&ctx);
1247 hmac_update_chunk(&ctx, st->st_skeyid_d);
1248 hmac_update_chunk(&ctx, st->st_shared);
1249 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1250 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1251 hmac_update(&ctx, "\1", 1);
1252 hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1253
1254 /* SKEYID_E */
1255 hmac_reinit(&ctx);
1256 hmac_update_chunk(&ctx, st->st_skeyid_a);
1257 hmac_update_chunk(&ctx, st->st_shared);
1258 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1259 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1260 hmac_update(&ctx, "\2", 1);
1261 hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1262 }
1263
1264 /* generate IV */
1265 {
1266 union hash_ctx hash_ctx;
1267 const struct hash_desc *h = st->st_oakley.hasher;
1268
1269 st->st_new_iv_len = h->hash_digest_size;
1270 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1271
1272 DBG(DBG_CRYPT,
1273 DBG_dump_chunk("DH_i:", st->st_gi);
1274 DBG_dump_chunk("DH_r:", st->st_gr);
1275 );
1276 h->hash_init(&hash_ctx);
1277 h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1278 h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1279 h->hash_final(st->st_new_iv, &hash_ctx);
1280 }
1281
1282 /* Oakley Keying Material
1283 * Derived from Skeyid_e: if it is not big enough, generate more
1284 * using the PRF.
1285 * See RFC 2409 "IKE" Appendix B
1286 */
1287 {
1288 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1289 const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1290 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1291 u_char *k = st->st_skeyid_e.ptr;
1292
1293 if (keysize > st->st_skeyid_e.len)
1294 {
1295 struct hmac_ctx ctx;
1296 size_t i = 0;
1297
1298 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1299 hmac_update(&ctx, "\0", 1);
1300 for (;;)
1301 {
1302 hmac_final(&keytemp[i], &ctx);
1303 i += ctx.hmac_digest_size;
1304 if (i >= keysize)
1305 break;
1306 hmac_reinit(&ctx);
1307 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1308 }
1309 k = keytemp;
1310 }
1311 clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1312 }
1313
1314 DBG(DBG_CRYPT,
1315 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1316 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1317 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1318 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1319 DBG_dump_chunk("enc key:", st->st_enc_key);
1320 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1321 return TRUE;
1322 }
1323
1324 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1325 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1326 * New Group Mode, or ISAKMP Informational Exchanges).
1327 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1328 * If hashus argument is TRUE, we're generating a hash for our end.
1329 * See RFC2409 IKE 5.
1330 *
1331 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1332 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1333 * The extensive common logic is embodied in main_mode_hash_body().
1334 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1335 */
1336
1337 typedef void (*hash_update_t)(union hash_ctx *, const u_char *, size_t) ;
1338 static void
1339 main_mode_hash_body(struct state *st
1340 , bool hashi /* Initiator? */
1341 , const pb_stream *idpl /* ID payload, as PBS */
1342 , union hash_ctx *ctx
1343 , void (*hash_update_void)(void *, const u_char *input, size_t))
1344 {
1345 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1346 hash_update_t hash_update=(hash_update_t) hash_update_void;
1347 #if 0 /* if desperate to debug hashing */
1348 # define hash_update(ctx, input, len) { \
1349 DBG_dump("hash input", input, len); \
1350 (hash_update)(ctx, input, len); \
1351 }
1352 #endif
1353
1354 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1355
1356 if (hashi)
1357 {
1358 hash_update_chunk(ctx, st->st_gi);
1359 hash_update_chunk(ctx, st->st_gr);
1360 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1361 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1362 }
1363 else
1364 {
1365 hash_update_chunk(ctx, st->st_gr);
1366 hash_update_chunk(ctx, st->st_gi);
1367 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1368 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1369 }
1370
1371 DBG(DBG_CRYPT, DBG_log("hashing %lu bytes of SA"
1372 , (unsigned long) (st->st_p1isa.len - sizeof(struct isakmp_generic))));
1373
1374 /* SA_b */
1375 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1376 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1377
1378 /* Hash identification payload, without generic payload header.
1379 * We used to reconstruct ID Payload for this purpose, but now
1380 * we use the bytes as they appear on the wire to avoid
1381 * "spelling problems".
1382 */
1383 hash_update(ctx
1384 , idpl->start + sizeof(struct isakmp_generic)
1385 , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1386
1387 # undef hash_update_chunk
1388 # undef hash_update
1389 }
1390
1391 static size_t /* length of hash */
1392 main_mode_hash(struct state *st
1393 , u_char *hash_val /* resulting bytes */
1394 , bool hashi /* Initiator? */
1395 , const pb_stream *idpl) /* ID payload, as PBS; cur must be at end */
1396 {
1397 struct hmac_ctx ctx;
1398
1399 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1400 main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1401 hmac_final(hash_val, &ctx);
1402 return ctx.hmac_digest_size;
1403 }
1404
1405 #if 0 /* only needed for DSS */
1406 static void
1407 main_mode_sha1(struct state *st
1408 , u_char *hash_val /* resulting bytes */
1409 , size_t *hash_len /* length of hash */
1410 , bool hashi /* Initiator? */
1411 , const pb_stream *idpl) /* ID payload, as PBS */
1412 {
1413 union hash_ctx ctx;
1414
1415 SHA1Init(&ctx.ctx_sha1);
1416 SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1417 *hash_len = SHA1_DIGEST_SIZE;
1418 main_mode_hash_body(st, hashi, idpl, &ctx
1419 , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1420 SHA1Final(hash_val, &ctx.ctx_sha1);
1421 }
1422 #endif
1423
1424 /* Create an RSA signature of a hash.
1425 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1426 * Use PKCS#1 version 1.5 encryption of hash (called
1427 * RSAES-PKCS1-V1_5) in PKCS#2.
1428 */
1429 static size_t
1430 RSA_sign_hash(struct connection *c
1431 , u_char sig_val[RSA_MAX_OCTETS]
1432 , const u_char *hash_val, size_t hash_len)
1433 {
1434 size_t sz = 0;
1435 smartcard_t *sc = c->spd.this.sc;
1436
1437 if (sc == NULL) /* no smartcard */
1438 {
1439 const struct RSA_private_key *k = get_RSA_private_key(c);
1440
1441 if (k == NULL)
1442 return 0; /* failure: no key to use */
1443
1444 sz = k->pub.k;
1445 passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1446 sign_hash(k, hash_val, hash_len, sig_val, sz);
1447 }
1448 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1449 {
1450 lock_certs_and_keys("RSA_sign_hash");
1451 if (!scx_establish_context(sc) || !scx_login(sc))
1452 {
1453 scx_release_context(sc);
1454 unlock_certs_and_keys("RSA_sign_hash");
1455 return 0;
1456 }
1457
1458 sz = scx_get_keylength(sc);
1459 if (sz == 0)
1460 {
1461 plog("failed to get keylength from smartcard");
1462 scx_release_context(sc);
1463 unlock_certs_and_keys("RSA_sign_hash");
1464 return 0;
1465 }
1466
1467 DBG(DBG_CONTROL | DBG_CRYPT,
1468 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1469 , (int)sc->slot, sc->id)
1470 )
1471 sz = scx_sign_hash(sc, hash_val, hash_len, sig_val, sz) ? sz : 0;
1472 if (!pkcs11_keep_state)
1473 scx_release_context(sc);
1474 unlock_certs_and_keys("RSA_sign_hash");
1475 }
1476 return sz;
1477 }
1478
1479 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1480 *
1481 * As a side effect, on success, the public key is copied into the
1482 * state object to record the authenticator.
1483 *
1484 * Can fail because wrong public key is used or because hash disagrees.
1485 * We distinguish because diagnostics should also.
1486 *
1487 * The result is NULL if the Signature checked out.
1488 * Otherwise, the first character of the result indicates
1489 * how far along failure occurred. A greater character signifies
1490 * greater progress.
1491 *
1492 * Classes:
1493 * 0 reserved for caller
1494 * 1 SIG length doesn't match key length -- wrong key
1495 * 2-8 malformed ECB after decryption -- probably wrong key
1496 * 9 decrypted hash != computed hash -- probably correct key
1497 *
1498 * Although the math should be the same for generating and checking signatures,
1499 * it is not: the knowledge of the private key allows more efficient (i.e.
1500 * different) computation for encryption.
1501 */
1502 static err_t
1503 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1504 , const pb_stream *sig_pbs, pubkey_t *kr
1505 , struct state *st)
1506 {
1507 const u_char *sig_val = sig_pbs->cur;
1508 size_t sig_len = pbs_left(sig_pbs);
1509 u_char s[RSA_MAX_OCTETS]; /* for decrypted sig_val */
1510 u_char *hash_in_s = &s[sig_len - hash_len];
1511 const struct RSA_public_key *k = &kr->u.rsa;
1512
1513 /* decrypt the signature -- reversing RSA_sign_hash */
1514 if (sig_len != k->k)
1515 {
1516 /* XXX notification: INVALID_KEY_INFORMATION */
1517 return "1" "SIG length does not match public key length";
1518 }
1519
1520 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1521 {
1522 chunk_t temp_s;
1523 mpz_t c;
1524
1525 n_to_mpz(c, sig_val, sig_len);
1526 mpz_powm(c, c, &k->e, &k->n);
1527
1528 temp_s = mpz_to_n(c, sig_len); /* back to octets */
1529 memcpy(s, temp_s.ptr, sig_len);
1530 pfree(temp_s.ptr);
1531 mpz_clear(c);
1532 }
1533
1534 /* sanity check on signature: see if it matches
1535 * PKCS#1 v1.5 8.1 encryption-block formatting
1536 */
1537 {
1538 err_t ugh = NULL;
1539
1540 if (s[0] != 0x00)
1541 ugh = "2" "no leading 00";
1542 else if (hash_in_s[-1] != 0x00)
1543 ugh = "3" "00 separator not present";
1544 else if (s[1] == 0x01)
1545 {
1546 const u_char *p;
1547
1548 for (p = &s[2]; p != hash_in_s - 1; p++)
1549 {
1550 if (*p != 0xFF)
1551 {
1552 ugh = "4" "invalid Padding String";
1553 break;
1554 }
1555 }
1556 }
1557 else if (s[1] == 0x02)
1558 {
1559 const u_char *p;
1560
1561 for (p = &s[2]; p != hash_in_s - 1; p++)
1562 {
1563 if (*p == 0x00)
1564 {
1565 ugh = "5" "invalid Padding String";
1566 break;
1567 }
1568 }
1569 }
1570 else
1571 ugh = "6" "Block Type not 01 or 02";
1572
1573 if (ugh != NULL)
1574 {
1575 /* note: it might be a good idea to make sure that
1576 * an observer cannot tell what kind of failure happened.
1577 * I don't know what this means in practice.
1578 */
1579 /* We probably selected the wrong public key for peer:
1580 * SIG Payload decrypted into malformed ECB
1581 */
1582 /* XXX notification: INVALID_KEY_INFORMATION */
1583 return ugh;
1584 }
1585 }
1586
1587 /* We have the decoded hash: see if it matches. */
1588 if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1589 {
1590 /* good: header, hash, signature, and other payloads well-formed
1591 * good: we could find an RSA Sig key for the peer.
1592 * bad: hash doesn't match
1593 * Guess: sides disagree about key to be used.
1594 */
1595 DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1596 DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1597 /* XXX notification: INVALID_HASH_INFORMATION */
1598 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1599 }
1600
1601 /* Success: copy successful key into state.
1602 * There might be an old one if we previously aborted this
1603 * state transition.
1604 */
1605 unreference_key(&st->st_peer_pubkey);
1606 st->st_peer_pubkey = reference_key(kr);
1607
1608 return NULL; /* happy happy */
1609 }
1610
1611 /* Check signature against all RSA public keys we can find.
1612 * If we need keys from DNS KEY records, and they haven't been fetched,
1613 * return STF_SUSPEND to ask for asynch DNS lookup.
1614 *
1615 * Note: parameter keys_from_dns contains results of DNS lookup for key
1616 * or is NULL indicating lookup not yet tried.
1617 *
1618 * take_a_crack is a helper function. Mostly forensic.
1619 * If only we had coroutines.
1620 */
1621 struct tac_state {
1622 /* RSA_check_signature's args that take_a_crack needs */
1623 struct state *st;
1624 const u_char *hash_val;
1625 size_t hash_len;
1626 const pb_stream *sig_pbs;
1627
1628 /* state carried between calls */
1629 err_t best_ugh; /* most successful failure */
1630 int tried_cnt; /* number of keys tried */
1631 char tried[50]; /* keyids of tried public keys */
1632 char *tn; /* roof of tried[] */
1633 };
1634
1635 static bool
1636 take_a_crack(struct tac_state *s
1637 , pubkey_t *kr
1638 , const char *story USED_BY_DEBUG)
1639 {
1640 err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1641 , kr, s->st);
1642 const struct RSA_public_key *k = &kr->u.rsa;
1643
1644 s->tried_cnt++;
1645 if (ugh == NULL)
1646 {
1647 DBG(DBG_CRYPT | DBG_CONTROL
1648 , DBG_log("an RSA Sig check passed with *%s [%s]"
1649 , k->keyid, story));
1650 return TRUE;
1651 }
1652 else
1653 {
1654 DBG(DBG_CRYPT
1655 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1656 , ugh + 1, k->keyid, story));
1657 if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1658 s->best_ugh = ugh;
1659 if (ugh[0] > '0'
1660 && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1661 {
1662 strcpy(s->tn, " *");
1663 strcpy(s->tn + 2, k->keyid);
1664 s->tn += strlen(s->tn);
1665 }
1666 return FALSE;
1667 }
1668 }
1669
1670 static stf_status
1671 RSA_check_signature(const struct id* peer
1672 , struct state *st
1673 , const u_char hash_val[MAX_DIGEST_LEN]
1674 , size_t hash_len
1675 , const pb_stream *sig_pbs
1676 #ifdef USE_KEYRR
1677 , const pubkey_list_t *keys_from_dns
1678 #endif /* USE_KEYRR */
1679 , const struct gw_info *gateways_from_dns
1680 )
1681 {
1682 const struct connection *c = st->st_connection;
1683 struct tac_state s;
1684 err_t dns_ugh = NULL;
1685
1686 s.st = st;
1687 s.hash_val = hash_val;
1688 s.hash_len = hash_len;
1689 s.sig_pbs = sig_pbs;
1690
1691 s.best_ugh = NULL;
1692 s.tried_cnt = 0;
1693 s.tn = s.tried;
1694
1695 /* try all gateway records hung off c */
1696 if (c->policy & POLICY_OPPO)
1697 {
1698 struct gw_info *gw;
1699
1700 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1701 {
1702 /* only consider entries that have a key and are for our peer */
1703 if (gw->gw_key_present
1704 && same_id(&gw->gw_id, &c->spd.that.id)
1705 && take_a_crack(&s, gw->key, "key saved from DNS TXT"))
1706 return STF_OK;
1707 }
1708 }
1709
1710 /* try all appropriate Public keys */
1711 {
1712 pubkey_list_t *p, **pp;
1713
1714 pp = &pubkeys;
1715
1716 for (p = pubkeys; p != NULL; p = *pp)
1717 {
1718 pubkey_t *key = p->key;
1719
1720 if (key->alg == PUBKEY_ALG_RSA && same_id(peer, &key->id))
1721 {
1722 time_t now = time(NULL);
1723
1724 /* check if found public key has expired */
1725 if (key->until_time != UNDEFINED_TIME && key->until_time < now)
1726 {
1727 loglog(RC_LOG_SERIOUS,
1728 "cached RSA public key has expired and has been deleted");
1729 *pp = free_public_keyentry(p);
1730 continue; /* continue with next public key */
1731 }
1732
1733 if (take_a_crack(&s, key, "preloaded key"))
1734 return STF_OK;
1735 }
1736 pp = &p->next;
1737 }
1738 }
1739
1740 /* if no key was found (evidenced by best_ugh == NULL)
1741 * and that side of connection is key_from_DNS_on_demand
1742 * then go search DNS for keys for peer.
1743 */
1744 if (s.best_ugh == NULL && c->spd.that.key_from_DNS_on_demand)
1745 {
1746 if (gateways_from_dns != NULL)
1747 {
1748 /* TXT keys */
1749 const struct gw_info *gwp;
1750
1751 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1752 if (gwp->gw_key_present
1753 && take_a_crack(&s, gwp->key, "key from DNS TXT"))
1754 return STF_OK;
1755 }
1756 #ifdef USE_KEYRR
1757 else if (keys_from_dns != NULL)
1758 {
1759 /* KEY keys */
1760 const pubkey_list_t *kr;
1761
1762 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1763 if (kr->key->alg == PUBKEY_ALG_RSA
1764 && take_a_crack(&s, kr->key, "key from DNS KEY"))
1765 return STF_OK;
1766 }
1767 #endif /* USE_KEYRR */
1768 else
1769 {
1770 /* nothing yet: ask for asynch DNS lookup */
1771 return STF_SUSPEND;
1772 }
1773 }
1774
1775 /* no acceptable key was found: diagnose */
1776 {
1777 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
1778
1779 (void) idtoa(peer, id_buf, sizeof(id_buf));
1780
1781 if (s.best_ugh == NULL)
1782 {
1783 if (dns_ugh == NULL)
1784 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1785 , id_buf);
1786 else
1787 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1788 "; DNS search for KEY failed (%s)"
1789 , id_buf, dns_ugh);
1790
1791 /* ??? is this the best code there is? */
1792 return STF_FAIL + INVALID_KEY_INFORMATION;
1793 }
1794
1795 if (s.best_ugh[0] == '9')
1796 {
1797 loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1798 /* XXX Could send notification back */
1799 return STF_FAIL + INVALID_HASH_INFORMATION;
1800 }
1801 else
1802 {
1803 if (s.tried_cnt == 1)
1804 {
1805 loglog(RC_LOG_SERIOUS
1806 , "Signature check (on %s) failed (wrong key?); tried%s"
1807 , id_buf, s.tried);
1808 DBG(DBG_CONTROL,
1809 DBG_log("public key for %s failed:"
1810 " decrypted SIG payload into a malformed ECB (%s)"
1811 , id_buf, s.best_ugh + 1));
1812 }
1813 else
1814 {
1815 loglog(RC_LOG_SERIOUS
1816 , "Signature check (on %s) failed:"
1817 " tried%s keys but none worked."
1818 , id_buf, s.tried);
1819 DBG(DBG_CONTROL,
1820 DBG_log("all %d public keys for %s failed:"
1821 " best decrypted SIG payload into a malformed ECB (%s)"
1822 , s.tried_cnt, id_buf, s.best_ugh + 1));
1823 }
1824 return STF_FAIL + INVALID_KEY_INFORMATION;
1825 }
1826 }
1827 }
1828
1829 static notification_t
1830 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
1831 {
1832 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
1833 size_t len = pbs_left(nonce_pbs);
1834
1835 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
1836 {
1837 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
1838 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
1839 return PAYLOAD_MALFORMED; /* ??? */
1840 }
1841 clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
1842 return NOTHING_WRONG;
1843 }
1844
1845 /* encrypt message, sans fixed part of header
1846 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1847 * The theory is that there will be no "backing out", so we commit to IV.
1848 * We also close the pbs.
1849 */
1850 bool
1851 encrypt_message(pb_stream *pbs, struct state *st)
1852 {
1853 const struct encrypt_desc *e = st->st_oakley.encrypter;
1854 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
1855 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
1856
1857 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
1858
1859 /* Pad up to multiple of encryption blocksize.
1860 * See the description associated with the definition of
1861 * struct isakmp_hdr in packet.h.
1862 */
1863 {
1864 size_t padding = pad_up(enc_len, e->enc_blocksize);
1865
1866 if (padding != 0)
1867 {
1868 if (!out_zero(padding, pbs, "encryption padding"))
1869 return FALSE;
1870 enc_len += padding;
1871 }
1872 }
1873
1874 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1875
1876 /* e->crypt(TRUE, enc_start, enc_len, st); */
1877 crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
1878
1879 update_iv(st);
1880 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
1881 close_message(pbs);
1882 return TRUE;
1883 }
1884
1885 /* Compute HASH(1), HASH(2) of Quick Mode.
1886 * HASH(1) is part of Quick I1 message.
1887 * HASH(2) is part of Quick R1 message.
1888 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1889 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1890 */
1891 static size_t
1892 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
1893 , const struct state *st, const msgid_t *msgid, bool hash2)
1894 {
1895 struct hmac_ctx ctx;
1896
1897 #if 0 /* if desperate to debug hashing */
1898 # define hmac_update(ctx, ptr, len) { \
1899 DBG_dump("hash input", (ptr), (len)); \
1900 (hmac_update)((ctx), (ptr), (len)); \
1901 }
1902 DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
1903 #endif
1904 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1905 hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
1906 if (hash2)
1907 hmac_update_chunk(&ctx, st->st_ni); /* include Ni_b in the hash */
1908 hmac_update(&ctx, start, roof-start);
1909 hmac_final(dest, &ctx);
1910
1911 DBG(DBG_CRYPT,
1912 DBG_log("HASH(%d) computed:", hash2 + 1);
1913 DBG_dump("", dest, ctx.hmac_digest_size));
1914 return ctx.hmac_digest_size;
1915 # undef hmac_update
1916 }
1917
1918 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1919 * Used by: quick_inR1_outI2, quick_inI2
1920 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1921 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1922 * Message ID and Nonces. This is a mistake.
1923 */
1924 static size_t
1925 quick_mode_hash3(u_char *dest, struct state *st)
1926 {
1927 struct hmac_ctx ctx;
1928
1929 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1930 hmac_update(&ctx, "\0", 1);
1931 hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
1932 hmac_update_chunk(&ctx, st->st_ni);
1933 hmac_update_chunk(&ctx, st->st_nr);
1934 hmac_final(dest, &ctx);
1935 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
1936 return ctx.hmac_digest_size;
1937 }
1938
1939 /* Compute Phase 2 IV.
1940 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1941 */
1942 void
1943 init_phase2_iv(struct state *st, const msgid_t *msgid)
1944 {
1945 const struct hash_desc *h = st->st_oakley.hasher;
1946 union hash_ctx ctx;
1947
1948 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
1949 , st->st_ph1_iv, st->st_ph1_iv_len);
1950
1951 st->st_new_iv_len = h->hash_digest_size;
1952 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1953
1954 h->hash_init(&ctx);
1955 h->hash_update(&ctx, st->st_ph1_iv, st->st_ph1_iv_len);
1956 passert(*msgid != 0);
1957 h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
1958 h->hash_final(st->st_new_iv, &ctx);
1959
1960 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
1961 , st->st_new_iv, st->st_new_iv_len);
1962 }
1963
1964 /* Initiate quick mode.
1965 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1966 * (see RFC 2409 "IKE" 5.5)
1967 * Note: this is not called from demux.c
1968 */
1969
1970 static bool
1971 emit_subnet_id(ip_subnet *net
1972 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
1973 {
1974 struct isakmp_ipsec_id id;
1975 pb_stream id_pbs;
1976 ip_address ta;
1977 const unsigned char *tbp;
1978 size_t tal;
1979
1980 id.isaiid_np = np;
1981 id.isaiid_idtype = subnetishost(net)
1982 ? aftoinfo(subnettypeof(net))->id_addr
1983 : aftoinfo(subnettypeof(net))->id_subnet;
1984 id.isaiid_protoid = protoid;
1985 id.isaiid_port = port;
1986
1987 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
1988 return FALSE;
1989
1990 networkof(net, &ta);
1991 tal = addrbytesptr(&ta, &tbp);
1992 if (!out_raw(tbp, tal, &id_pbs, "client network"))
1993 return FALSE;
1994
1995 if (!subnetishost(net))
1996 {
1997 maskof(net, &ta);
1998 tal = addrbytesptr(&ta, &tbp);
1999 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2000 return FALSE;
2001 }
2002
2003 close_output_pbs(&id_pbs);
2004 return TRUE;
2005 }
2006
2007 stf_status
2008 quick_outI1(int whack_sock
2009 , struct state *isakmp_sa
2010 , struct connection *c
2011 , lset_t policy
2012 , unsigned long try
2013 , so_serial_t replacing)
2014 {
2015 struct state *st = duplicate_state(isakmp_sa);
2016 pb_stream reply; /* not really a reply */
2017 pb_stream rbody;
2018 u_char /* set by START_HASH_PAYLOAD: */
2019 *r_hashval, /* where in reply to jam hash value */
2020 *r_hash_start; /* start of what is to be hashed */
2021 bool has_client = c->spd.this.has_client || c->spd.that.has_client ||
2022 c->spd.this.protocol || c->spd.that.protocol ||
2023 c->spd.this.port || c->spd.that.port;
2024
2025 bool send_natoa = FALSE;
2026 u_int8_t np = ISAKMP_NEXT_NONE;
2027
2028 st->st_whack_sock = whack_sock;
2029 st->st_connection = c;
2030 set_cur_state(st); /* we must reset before exit */
2031 st->st_policy = policy;
2032 st->st_try = try;
2033
2034 st->st_myuserprotoid = c->spd.this.protocol;
2035 st->st_peeruserprotoid = c->spd.that.protocol;
2036 st->st_myuserport = c->spd.this.port;
2037 st->st_peeruserport = c->spd.that.port;
2038
2039 st->st_msgid = generate_msgid(isakmp_sa);
2040 st->st_state = STATE_QUICK_I1;
2041
2042 insert_state(st); /* needs cookies, connection, and msgid */
2043
2044 if (replacing == SOS_NOBODY)
2045 plog("initiating Quick Mode %s {using isakmp#%lu}"
2046 , prettypolicy(policy)
2047 , isakmp_sa->st_serialno);
2048 else
2049 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2050 , prettypolicy(policy)
2051 , replacing
2052 , isakmp_sa->st_serialno);
2053
2054 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
2055 {
2056 /* Duplicate nat_traversal status in new state */
2057 st->nat_traversal = isakmp_sa->nat_traversal;
2058
2059 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
2060 has_client = TRUE;
2061
2062 nat_traversal_change_port_lookup(NULL, st);
2063 }
2064 else
2065 st->nat_traversal = 0;
2066
2067 /* are we going to send a NAT-OA payload? */
2068 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2069 && !(st->st_policy & POLICY_TUNNEL)
2070 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2071 {
2072 send_natoa = TRUE;
2073 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2074 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2075 }
2076
2077 /* set up reply */
2078 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2079
2080 /* HDR* out */
2081 {
2082 struct isakmp_hdr hdr;
2083
2084 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2085 hdr.isa_np = ISAKMP_NEXT_HASH;
2086 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2087 hdr.isa_msgid = st->st_msgid;
2088 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2089 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2090 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2091 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2092 {
2093 reset_cur_state();
2094 return STF_INTERNAL_ERROR;
2095 }
2096 }
2097
2098 /* HASH(1) -- create and note space to be filled later */
2099 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2100
2101 /* SA out */
2102
2103 /*
2104 * See if pfs_group has been specified for this conn,
2105 * if not, fallback to old use-same-as-P1 behaviour
2106 */
2107 #ifndef NO_IKE_ALG
2108 if (st->st_connection)
2109 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2110 if (!st->st_pfs_group)
2111 #endif
2112 /* If PFS specified, use the same group as during Phase 1:
2113 * since no negotiation is possible, we pick one that is
2114 * very likely supported.
2115 */
2116 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2117
2118 /* Emit SA payload based on a subset of the policy bits.
2119 * POLICY_COMPRESS is considered iff we can do IPcomp.
2120 */
2121 {
2122 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2123
2124 if (can_do_IPcomp)
2125 pm |= POLICY_COMPRESS;
2126
2127 if (!out_sa(&rbody
2128 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2129 , st, FALSE, ISAKMP_NEXT_NONCE))
2130 {
2131 reset_cur_state();
2132 return STF_INTERNAL_ERROR;
2133 }
2134 }
2135
2136 /* Ni out */
2137 if (!build_and_ship_nonce(&st->st_ni, &rbody
2138 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2139 , "Ni"))
2140 {
2141 reset_cur_state();
2142 return STF_INTERNAL_ERROR;
2143 }
2144
2145 /* [ KE ] out (for PFS) */
2146
2147 if (st->st_pfs_group != NULL)
2148 {
2149 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2150 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2151 {
2152 reset_cur_state();
2153 return STF_INTERNAL_ERROR;
2154 }
2155 }
2156
2157 /* [ IDci, IDcr ] out */
2158 if (has_client)
2159 {
2160 /* IDci (we are initiator), then IDcr (peer is responder) */
2161 if (!emit_subnet_id(&c->spd.this.client
2162 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2163 || !emit_subnet_id(&c->spd.that.client
2164 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2165 {
2166 reset_cur_state();
2167 return STF_INTERNAL_ERROR;
2168 }
2169 }
2170
2171 /* Send NAT-OA if our address is NATed */
2172 if (send_natoa)
2173 {
2174 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2175 {
2176 reset_cur_state();
2177 return STF_INTERNAL_ERROR;
2178 }
2179 }
2180
2181 /* finish computing HASH(1), inserting it in output */
2182 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2183 , st, &st->st_msgid, FALSE);
2184
2185 /* encrypt message, except for fixed part of header */
2186
2187 init_phase2_iv(isakmp_sa, &st->st_msgid);
2188 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2189 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2190
2191 if (!encrypt_message(&rbody, st))
2192 {
2193 reset_cur_state();
2194 return STF_INTERNAL_ERROR;
2195 }
2196
2197 /* save packet, now that we know its size */
2198 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2199 , "reply packet from quick_outI1");
2200
2201 /* send the packet */
2202
2203 send_packet(st, "quick_outI1");
2204
2205 delete_event(st);
2206 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2207
2208 if (replacing == SOS_NOBODY)
2209 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2210 , "%s: initiate"
2211 , enum_name(&state_names, st->st_state));
2212 else
2213 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2214 , "%s: initiate to replace #%lu"
2215 , enum_name(&state_names, st->st_state)
2216 , replacing);
2217 reset_cur_state();
2218 return STF_OK;
2219 }
2220
2221
2222 /*
2223 * Decode the CERT payload of Phase 1.
2224 */
2225 static void
2226 decode_cert(struct msg_digest *md)
2227 {
2228 struct payload_digest *p;
2229
2230 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2231 {
2232 struct isakmp_cert *const cert = &p->payload.cert;
2233 chunk_t blob;
2234 time_t valid_until;
2235 blob.ptr = p->pbs.cur;
2236 blob.len = pbs_left(&p->pbs);
2237 if (cert->isacert_type == CERT_X509_SIGNATURE)
2238 {
2239 x509cert_t cert = empty_x509cert;
2240 if (parse_x509cert(blob, 0, &cert))
2241 {
2242 if (verify_x509cert(&cert, strict_crl_policy, &valid_until))
2243 {
2244 DBG(DBG_PARSING,
2245 DBG_log("Public key validated")
2246 )
2247 add_x509_public_key(&cert, valid_until, DAL_SIGNED);
2248 }
2249 else
2250 {
2251 plog("X.509 certificate rejected");
2252 }
2253 free_generalNames(cert.subjectAltName, FALSE);
2254 free_generalNames(cert.crlDistributionPoints, FALSE);
2255 }
2256 else
2257 plog("Syntax error in X.509 certificate");
2258 }
2259 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2260 {
2261 x509cert_t *cert = NULL;
2262
2263 if (pkcs7_parse_signedData(blob, NULL, &cert, NULL, NULL))
2264 store_x509certs(&cert, strict_crl_policy);
2265 else
2266 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2267 }
2268 else
2269 {
2270 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2271 enum_show(&cert_type_names, cert->isacert_type));
2272 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2273 }
2274 }
2275 }
2276
2277 /*
2278 * Decode the CR payload of Phase 1.
2279 */
2280 static void
2281 decode_cr(struct msg_digest *md, struct connection *c)
2282 {
2283 struct payload_digest *p;
2284
2285 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2286 {
2287 struct isakmp_cr *const cr = &p->payload.cr;
2288 chunk_t ca_name;
2289
2290 ca_name.len = pbs_left(&p->pbs);
2291 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2292
2293 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2294
2295 if (cr->isacr_type == CERT_X509_SIGNATURE)
2296 {
2297 char buf[BUF_LEN];
2298
2299 if (ca_name.len > 0)
2300 {
2301 generalName_t *gn;
2302
2303 if (!is_asn1(ca_name))
2304 continue;
2305
2306 gn = alloc_thing(generalName_t, "generalName");
2307 clonetochunk(ca_name, ca_name.ptr,ca_name.len, "ca name");
2308 gn->kind = GN_DIRECTORY_NAME;
2309 gn->name = ca_name;
2310 gn->next = c->requested_ca;
2311 c->requested_ca = gn;
2312 }
2313 c->got_certrequest = TRUE;
2314
2315 DBG(DBG_PARSING | DBG_CONTROL,
2316 dntoa_or_null(buf, BUF_LEN, ca_name, "%any");
2317 DBG_log("requested CA: '%s'", buf);
2318 )
2319 }
2320 else
2321 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2322 enum_show(&cert_type_names, cr->isacr_type));
2323 }
2324 }
2325
2326 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2327 * Note: we may change connections as a result.
2328 * We must be called before SIG or HASH are decoded since we
2329 * may change the peer's RSA key or ID.
2330 */
2331 static bool
2332 decode_peer_id(struct msg_digest *md, struct id *peer)
2333 {
2334 struct state *const st = md->st;
2335 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2336 const pb_stream *const id_pbs = &id_pld->pbs;
2337 struct isakmp_id *const id = &id_pld->payload.id;
2338
2339 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2340 * It talks about the protocol ID and Port fields of the ID
2341 * Payload, but they don't exist as such in Phase 1.
2342 * We use more appropriate names.
2343 * isaid_doi_specific_a is in place of Protocol ID.
2344 * isaid_doi_specific_b is in place of Port.
2345 * Besides, there is no good reason for allowing these to be
2346 * other than 0 in Phase 1.
2347 */
2348 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2349 && id->isaid_doi_specific_a == IPPROTO_UDP
2350 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2351 {
2352 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2353 "accepted with port_floating NAT-T",
2354 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2355 }
2356 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2357 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2358 {
2359 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2360 " but are %d/%d"
2361 , IPPROTO_UDP, IKE_UDP_PORT
2362 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2363 return FALSE;
2364 }
2365
2366 peer->kind = id->isaid_idtype;
2367
2368 switch (peer->kind)
2369 {
2370 case ID_IPV4_ADDR:
2371 case ID_IPV6_ADDR:
2372 /* failure mode for initaddr is probably inappropriate address length */
2373 {
2374 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2375 , peer->kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2376 , &peer->ip_addr);
2377
2378 if (ugh != NULL)
2379 {
2380 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2381 , enum_show(&ident_names, peer->kind), ugh);
2382 /* XXX Could send notification back */
2383 return FALSE;
2384 }
2385 }
2386 break;
2387
2388 case ID_USER_FQDN:
2389 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2390 {
2391 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2392 return FALSE;
2393 }
2394 /* FALLTHROUGH */
2395 case ID_FQDN:
2396 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2397 {
2398 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2399 , enum_show(&ident_names, peer->kind));
2400 return FALSE;
2401 }
2402
2403 /* ??? ought to do some more sanity check, but what? */
2404
2405 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2406 break;
2407
2408 case ID_KEY_ID:
2409 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2410 DBG(DBG_PARSING,
2411 DBG_dump_chunk("KEY ID:", peer->name));
2412 break;
2413
2414 case ID_DER_ASN1_DN:
2415 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2416 DBG(DBG_PARSING,
2417 DBG_dump_chunk("DER ASN1 DN:", peer->name));
2418 break;
2419
2420 default:
2421 /* XXX Could send notification back */
2422 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2423 , enum_show(&ident_names, peer->kind));
2424 return FALSE;
2425 }
2426
2427 {
2428 char buf[BUF_LEN];
2429
2430 idtoa(peer, buf, sizeof(buf));
2431 plog("Peer ID is %s: '%s'",
2432 enum_show(&ident_names, id->isaid_idtype), buf);
2433 }
2434
2435 /* check for certificates */
2436 decode_cert(md);
2437 return TRUE;
2438 }
2439
2440 /* Now that we've decoded the ID payload, let's see if we
2441 * need to switch connections.
2442 * We must not switch horses if we initiated:
2443 * - if the initiation was explicit, we'd be ignoring user's intent
2444 * - if opportunistic, we'll lose our HOLD info
2445 */
2446 static bool
2447 switch_connection(struct msg_digest *md, struct id *peer, bool initiator)
2448 {
2449 struct state *const st = md->st;
2450 struct connection *c = st->st_connection;
2451
2452 chunk_t peer_ca = (st->st_peer_pubkey != NULL)
2453 ? st->st_peer_pubkey->issuer : empty_chunk;
2454
2455 DBG(DBG_CONTROL,
2456 char buf[BUF_LEN];
2457
2458 dntoa_or_null(buf, BUF_LEN, peer_ca, "%none");
2459 DBG_log("peer CA: '%s'", buf);
2460 )
2461
2462 if (initiator)
2463 {
2464 int pathlen;
2465
2466 if (!same_id(&c->spd.that.id, peer))
2467 {
2468 char expect[BUF_LEN]
2469 , found[BUF_LEN];
2470
2471 idtoa(&c->spd.that.id, expect, sizeof(expect));
2472 idtoa(peer, found, sizeof(found));
2473 loglog(RC_LOG_SERIOUS
2474 , "we require peer to have ID '%s', but peer declares '%s'"
2475 , expect, found);
2476 return FALSE;
2477 }
2478
2479 DBG(DBG_CONTROL,
2480 char buf[BUF_LEN];
2481
2482 dntoa_or_null(buf, BUF_LEN, c->spd.this.ca, "%none");
2483 DBG_log("required CA: '%s'", buf);
2484 )
2485
2486 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2487 {
2488 loglog(RC_LOG_SERIOUS
2489 , "we don't accept the peer's CA");
2490 return FALSE;
2491 }
2492 }
2493 else
2494 {
2495 struct connection *r;
2496
2497 /* check for certificate requests */
2498 decode_cr(md, c);
2499
2500 r = refine_host_connection(st, peer, peer_ca);
2501
2502 /* delete the collected certificate requests */
2503 free_generalNames(c->requested_ca, TRUE);
2504 c->requested_ca = NULL;
2505
2506 if (r == NULL)
2507 {
2508 char buf[BUF_LEN];
2509
2510 idtoa(peer, buf, sizeof(buf));
2511 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2512 return FALSE;
2513 }
2514
2515 DBG(DBG_CONTROL,
2516 char buf[BUF_LEN];
2517
2518 dntoa_or_null(buf, BUF_LEN, r->spd.this.ca, "%none");
2519 DBG_log("offered CA: '%s'", buf);
2520 )
2521
2522 if (r != c)
2523 {
2524 /* apparently, r is an improvement on c -- replace */
2525
2526 DBG(DBG_CONTROL
2527 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2528 if (r->kind == CK_TEMPLATE)
2529 {
2530 /* instantiate it, filling in peer's ID */
2531 r = rw_instantiate(r, &c->spd.that.host_addr
2532 , c->spd.that.host_port, NULL, peer);
2533 }
2534
2535 /* copy certificate request info */
2536 r->got_certrequest = c->got_certrequest;
2537
2538 st->st_connection = r; /* kill reference to c */
2539 set_cur_connection(r);
2540 connection_discard(c);
2541 }
2542 else if (c->spd.that.has_id_wildcards)
2543 {
2544 free_id_content(&c->spd.that.id);
2545 c->spd.that.id = *peer;
2546 c->spd.that.has_id_wildcards = FALSE;
2547 unshare_id_content(&c->spd.that.id);
2548 }
2549 }
2550 return TRUE;
2551 }
2552
2553 /* Decode the variable part of an ID packet (during Quick Mode).
2554 * This is designed for packets that identify clients, not peers.
2555 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2556 * (1) it is wrong and (2) we use this value for inband signalling.
2557 */
2558 static bool
2559 decode_net_id(struct isakmp_ipsec_id *id
2560 , pb_stream *id_pbs
2561 , ip_subnet *net
2562 , const char *which)
2563 {
2564 const struct af_info *afi = NULL;
2565
2566 /* Note: the following may be a pointer into static memory
2567 * that may be recycled, but only if the type is not known.
2568 * That case is disposed of very early -- in the first switch.
2569 */
2570 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2571
2572 switch (id->isaiid_idtype)
2573 {
2574 case ID_IPV4_ADDR:
2575 case ID_IPV4_ADDR_SUBNET:
2576 case ID_IPV4_ADDR_RANGE:
2577 afi = &af_inet4_info;
2578 break;
2579 case ID_IPV6_ADDR:
2580 case ID_IPV6_ADDR_SUBNET:
2581 case ID_IPV6_ADDR_RANGE:
2582 afi = &af_inet6_info;
2583 break;
2584 case ID_FQDN:
2585 return TRUE;
2586 default:
2587 /* XXX support more */
2588 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2589 , idtypename);
2590 /* XXX Could send notification back */
2591 return FALSE;
2592 }
2593
2594 switch (id->isaiid_idtype)
2595 {
2596 case ID_IPV4_ADDR:
2597 case ID_IPV6_ADDR:
2598 {
2599 ip_address temp_address;
2600 err_t ugh;
2601
2602 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2603
2604 if (ugh != NULL)
2605 {
2606 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2607 , which, idtypename, ugh);
2608 /* XXX Could send notification back */
2609 return FALSE;
2610 }
2611 if (isanyaddr(&temp_address))
2612 {
2613 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2614 , which, idtypename, ip_str(&temp_address));
2615 /* XXX Could send notification back */
2616 return FALSE;
2617 }
2618 happy(addrtosubnet(&temp_address, net));
2619 DBG(DBG_PARSING | DBG_CONTROL
2620 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2621 break;
2622 }
2623
2624 case ID_IPV4_ADDR_SUBNET:
2625 case ID_IPV6_ADDR_SUBNET:
2626 {
2627 ip_address temp_address, temp_mask;
2628 err_t ugh;
2629
2630 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2631 {
2632 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2633 , which, idtypename);
2634 /* XXX Could send notification back */
2635 return FALSE;
2636 }
2637 ugh = initaddr(id_pbs->cur
2638 , afi->ia_sz, afi->af, &temp_address);
2639 if (ugh == NULL)
2640 ugh = initaddr(id_pbs->cur + afi->ia_sz
2641 , afi->ia_sz, afi->af, &temp_mask);
2642 if (ugh == NULL)
2643 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2644 , '0', net);
2645 if (ugh == NULL && subnetisnone(net))
2646 ugh = "contains only anyaddr";
2647 if (ugh != NULL)
2648 {
2649 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2650 , which, idtypename, ugh);
2651 /* XXX Could send notification back */
2652 return FALSE;
2653 }
2654 DBG(DBG_PARSING | DBG_CONTROL,
2655 {
2656 char temp_buff[SUBNETTOT_BUF];
2657
2658 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2659 DBG_log("%s is subnet %s", which, temp_buff);
2660 });
2661 break;
2662 }
2663
2664 case ID_IPV4_ADDR_RANGE:
2665 case ID_IPV6_ADDR_RANGE:
2666 {
2667 ip_address temp_address_from, temp_address_to;
2668 err_t ugh;
2669
2670 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2671 {
2672 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2673 , which, idtypename);
2674 /* XXX Could send notification back */
2675 return FALSE;
2676 }
2677 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2678 if (ugh == NULL)
2679 ugh = initaddr(id_pbs->cur + afi->ia_sz
2680 , afi->ia_sz, afi->af, &temp_address_to);
2681 if (ugh != NULL)
2682 {
2683 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2684 , which, idtypename, ugh);
2685 /* XXX Could send notification back */
2686 return FALSE;
2687 }
2688
2689 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2690 if (ugh == NULL && subnetisnone(net))
2691 ugh = "contains only anyaddr";
2692 if (ugh != NULL)
2693 {
2694 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2695
2696 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2697 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2698 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2699 " %s - %s unacceptable: %s"
2700 , which, idtypename, temp_buff1, temp_buff2, ugh);
2701 return FALSE;
2702 }
2703 DBG(DBG_PARSING | DBG_CONTROL,
2704 {
2705 char temp_buff[SUBNETTOT_BUF];
2706
2707 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2708 DBG_log("%s is subnet %s (received as range)"
2709 , which, temp_buff);
2710 });
2711 break;
2712 }
2713 }
2714
2715 /* set the port selector */
2716 setportof(htons(id->isaiid_port), &net->addr);
2717
2718 DBG(DBG_PARSING | DBG_CONTROL,
2719 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2720 )
2721
2722 return TRUE;
2723 }
2724
2725 /* like decode, but checks that what is received matches what was sent */
2726 static bool
2727
2728 check_net_id(struct isakmp_ipsec_id *id
2729 , pb_stream *id_pbs
2730 , u_int8_t *protoid
2731 , u_int16_t *port
2732 , ip_subnet *net
2733 , const char *which)
2734 {
2735 ip_subnet net_temp;
2736
2737 if (!decode_net_id(id, id_pbs, &net_temp, which))
2738 return FALSE;
2739
2740 if (!samesubnet(net, &net_temp)
2741 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2742 {
2743 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2744 return FALSE;
2745 }
2746 return TRUE;
2747 }
2748
2749 /*
2750 * look for the existence of a non-expiring preloaded public key
2751 */
2752 static bool
2753 has_preloaded_public_key(struct state *st)
2754 {
2755 struct connection *c = st->st_connection;
2756
2757 /* do not consider rw connections since
2758 * the peer's identity must be known
2759 */
2760 if (c->kind == CK_PERMANENT)
2761 {
2762 pubkey_list_t *p;
2763
2764 /* look for a matching RSA public key */
2765 for (p = pubkeys; p != NULL; p = p->next)
2766 {
2767 pubkey_t *key = p->key;
2768
2769 if (key->alg == PUBKEY_ALG_RSA &&
2770 same_id(&c->spd.that.id, &key->id) &&
2771 key->until_time == UNDEFINED_TIME)
2772 {
2773 /* found a preloaded public key */
2774 return TRUE;
2775 }
2776 }
2777 }
2778 return FALSE;
2779 }
2780
2781 /*
2782 * Produce the new key material of Quick Mode.
2783 * RFC 2409 "IKE" section 5.5
2784 * specifies how this is to be done.
2785 */
2786 static void
2787 compute_proto_keymat(struct state *st
2788 , u_int8_t protoid
2789 , struct ipsec_proto_info *pi)
2790 {
2791 size_t needed_len; /* bytes of keying material needed */
2792
2793 /* Add up the requirements for keying material
2794 * (It probably doesn't matter if we produce too much!)
2795 */
2796 switch (protoid)
2797 {
2798 case PROTO_IPSEC_ESP:
2799 switch (pi->attrs.transid)
2800 {
2801 case ESP_NULL:
2802 needed_len = 0;
2803 break;
2804 case ESP_DES:
2805 needed_len = DES_CBC_BLOCK_SIZE;
2806 break;
2807 case ESP_3DES:
2808 needed_len = DES_CBC_BLOCK_SIZE * 3;
2809 break;
2810 default:
2811 #ifndef NO_KERNEL_ALG
2812 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2813 /* XXX: check key_len "coupling with kernel.c's */
2814 if (pi->attrs.key_len) {
2815 needed_len=pi->attrs.key_len/8;
2816 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2817 "key_len=%d from peer",
2818 (int)needed_len));
2819 }
2820 break;
2821 }
2822 #endif
2823 bad_case(pi->attrs.transid);
2824 }
2825
2826 #ifndef NO_KERNEL_ALG
2827 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2828 "needed_len (after ESP enc)=%d",
2829 (int)needed_len));
2830 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2831 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2832 } else
2833 #endif
2834 switch (pi->attrs.auth)
2835 {
2836 case AUTH_ALGORITHM_NONE:
2837 break;
2838 case AUTH_ALGORITHM_HMAC_MD5:
2839 needed_len += HMAC_MD5_KEY_LEN;
2840 break;
2841 case AUTH_ALGORITHM_HMAC_SHA1:
2842 needed_len += HMAC_SHA1_KEY_LEN;
2843 break;
2844 case AUTH_ALGORITHM_DES_MAC:
2845 default:
2846 bad_case(pi->attrs.auth);
2847 }
2848 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2849 "needed_len (after ESP auth)=%d",
2850 (int)needed_len));
2851 break;
2852
2853 case PROTO_IPSEC_AH:
2854 switch (pi->attrs.transid)
2855 {
2856 case AH_MD5:
2857 needed_len = HMAC_MD5_KEY_LEN;
2858 break;
2859 case AH_SHA:
2860 needed_len = HMAC_SHA1_KEY_LEN;
2861 break;
2862 default:
2863 bad_case(pi->attrs.transid);
2864 }
2865 break;
2866
2867 default:
2868 bad_case(protoid);
2869 }
2870
2871 pi->keymat_len = needed_len;
2872
2873 /* Allocate space for the keying material.
2874 * Although only needed_len bytes are desired, we
2875 * must round up to a multiple of ctx.hmac_digest_size
2876 * so that our buffer isn't overrun.
2877 */
2878 {
2879 struct hmac_ctx ctx_me, ctx_peer;
2880 size_t needed_space; /* space needed for keying material (rounded up) */
2881 size_t i;
2882
2883 hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
2884 ctx_peer = ctx_me; /* duplicate initial conditions */
2885
2886 needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
2887 replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
2888 replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
2889
2890 for (i = 0;; )
2891 {
2892 if (st->st_shared.ptr != NULL)
2893 {
2894 /* PFS: include the g^xy */
2895 hmac_update_chunk(&ctx_me, st->st_shared);
2896 hmac_update_chunk(&ctx_peer, st->st_shared);
2897 }
2898 hmac_update(&ctx_me, &protoid, sizeof(protoid));
2899 hmac_update(&ctx_peer, &protoid, sizeof(protoid));
2900
2901 hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
2902 hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
2903
2904 hmac_update_chunk(&ctx_me, st->st_ni);
2905 hmac_update_chunk(&ctx_peer, st->st_ni);
2906
2907 hmac_update_chunk(&ctx_me, st->st_nr);
2908 hmac_update_chunk(&ctx_peer, st->st_nr);
2909
2910 hmac_final(pi->our_keymat + i, &ctx_me);
2911 hmac_final(pi->peer_keymat + i, &ctx_peer);
2912
2913 i += ctx_me.hmac_digest_size;
2914 if (i >= needed_space)
2915 break;
2916
2917 /* more keying material needed: prepare to go around again */
2918
2919 hmac_reinit(&ctx_me);
2920 hmac_reinit(&ctx_peer);
2921
2922 hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size
2923 , ctx_me.hmac_digest_size);
2924 hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size
2925 , ctx_peer.hmac_digest_size);
2926 }
2927 }
2928
2929 DBG(DBG_CRYPT,
2930 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2931 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2932 }
2933
2934 static void
2935 compute_keymats(struct state *st)
2936 {
2937 if (st->st_ah.present)
2938 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2939 if (st->st_esp.present)
2940 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2941 }
2942
2943 /* State Transition Functions.
2944 *
2945 * The definition of state_microcode_table in demux.c is a good
2946 * overview of these routines.
2947 *
2948 * - Called from process_packet; result handled by complete_state_transition
2949 * - struct state_microcode member "processor" points to these
2950 * - these routine definitionss are in state order
2951 * - these routines must be restartable from any point of error return:
2952 * beware of memory allocated before any error.
2953 * - output HDR is usually emitted by process_packet (if state_microcode
2954 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2955 *
2956 * The transition functions' functions include:
2957 * - process and judge payloads
2958 * - update st_iv (result of decryption is in st_new_iv)
2959 * - build reply packet
2960 */
2961
2962 /* Handle a Main Mode Oakley first packet (responder side).
2963 * HDR;SA --> HDR;SA
2964 */
2965 stf_status
2966 main_inI1_outR1(struct msg_digest *md)
2967 {
2968 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2969 struct state *st;
2970 struct connection *c;
2971 struct isakmp_proposal proposal;
2972 pb_stream proposal_pbs;
2973 pb_stream r_sa_pbs;
2974 u_int32_t ipsecdoisit;
2975 lset_t policy = LEMPTY;
2976 int vids_to_send = 0;
2977
2978 /* We preparse the peer's proposal in order to determine
2979 * the requested authentication policy (RSA or PSK)
2980 */
2981 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2982 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2983
2984 backup_pbs(&proposal_pbs);
2985 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2986 , proposal.isap_notrans, &policy));
2987 restore_pbs(&proposal_pbs);
2988
2989 /* We are only considering candidate connections that match
2990 * the requested authentication policy (RSA or PSK)
2991 */
2992 c = find_host_connection(&md->iface->addr, pluto_port
2993 , &md->sender, md->sender_port, policy);
2994
2995 if (c == NULL && md->iface->ike_float)
2996 {
2997 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
2998 , &md->sender, md->sender_port, policy);
2999 }
3000
3001 if (c == NULL)
3002 {
3003 /* See if a wildcarded connection can be found.
3004 * We cannot pick the right connection, so we're making a guess.
3005 * All Road Warrior connections are fair game:
3006 * we pick the first we come across (if any).
3007 * If we don't find any, we pick the first opportunistic
3008 * with the smallest subnet that includes the peer.
3009 * There is, of course, no necessary relationship between
3010 * an Initiator's address and that of its client,
3011 * but Food Groups kind of assumes one.
3012 */
3013 {
3014 struct connection *d;
3015
3016 d = find_host_connection(&md->iface->addr
3017 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3018
3019 for (; d != NULL; d = d->hp_next)
3020 {
3021 if (d->kind == CK_GROUP)
3022 {
3023 /* ignore */
3024 }
3025 else
3026 {
3027 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3028 {
3029 /* must be Road Warrior: we have a winner */
3030 c = d;
3031 break;
3032 }
3033
3034 /* Opportunistic or Shunt: pick tightest match */
3035 if (addrinsubnet(&md->sender, &d->spd.that.client)
3036 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3037 c = d;
3038 }
3039 }
3040 }
3041
3042 if (c == NULL)
3043 {
3044 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3045 " but no connection has been authorized%s%s"
3046 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3047 , (policy != LEMPTY) ? " with policy=" : ""
3048 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3049 /* XXX notification is in order! */
3050 return STF_IGNORE;
3051 }
3052 else if (c->kind != CK_TEMPLATE)
3053 {
3054 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3055 " but \"%s\" forbids connection"
3056 , ip_str(&md->iface->addr), pluto_port, c->name);
3057 /* XXX notification is in order! */
3058 return STF_IGNORE;
3059 }
3060 else
3061 {
3062 /* Create a temporary connection that is a copy of this one.
3063 * His ID isn't declared yet.
3064 */
3065 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3066 }
3067 }
3068 else if (c->kind == CK_TEMPLATE)
3069 {
3070 /* Create an instance
3071 * This is a rare case: wildcard peer ID but static peer IP address
3072 */
3073 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, &c->spd.that.id);
3074 }
3075
3076 /* Set up state */
3077 md->st = st = new_state();
3078 st->st_connection = c;
3079 set_cur_state(st); /* (caller will reset cur_state) */
3080 st->st_try = 0; /* not our job to try again from start */
3081 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3082
3083 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3084 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3085
3086 insert_state(st); /* needs cookies, connection, and msgid (0) */
3087
3088 st->st_doi = ISAKMP_DOI_IPSEC;
3089 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3090
3091 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3092 {
3093 plog("responding to Main Mode from unknown peer %s:%u"
3094 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3095 }
3096 else if (c->kind == CK_INSTANCE)
3097 {
3098 plog("responding to Main Mode from unknown peer %s"
3099 , ip_str(&c->spd.that.host_addr));
3100 }
3101 else
3102 {
3103 plog("responding to Main Mode");
3104 }
3105
3106 /* parse_isakmp_sa also spits out a winning SA into our reply,
3107 * so we have to build our md->reply and emit HDR before calling it.
3108 */
3109
3110 /* determine how many Vendor ID payloads we will be sending */
3111 if (SEND_PLUTO_VID)
3112 vids_to_send++;
3113 if (SEND_CISCO_UNITY_VID)
3114 vids_to_send++;
3115 if (md->openpgp)
3116 vids_to_send++;
3117 /* always send XAUTH Vendor ID */
3118 vids_to_send++;
3119 /* always send DPD Vendor ID */
3120 vids_to_send++;
3121 if (md->nat_traversal_vid && nat_traversal_enabled)
3122 vids_to_send++;
3123
3124 /* HDR out.
3125 * We can't leave this to comm_handle() because we must
3126 * fill in the cookie.
3127 */
3128 {
3129 struct isakmp_hdr r_hdr = md->hdr;
3130
3131 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3132 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3133 r_hdr.isa_np = ISAKMP_NEXT_SA;
3134 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3135 return STF_INTERNAL_ERROR;
3136 }
3137
3138 /* start of SA out */
3139 {
3140 struct isakmp_sa r_sa = sa_pd->payload.sa;
3141
3142 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3143
3144 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3145 return STF_INTERNAL_ERROR;
3146 }
3147
3148 /* SA body in and out */
3149 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3150 ,&proposal, &r_sa_pbs, st, FALSE));
3151
3152 /* if enabled send Pluto Vendor ID */
3153 if (SEND_PLUTO_VID)
3154 {
3155 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3156 , &md->rbody, VID_STRONGSWAN))
3157 {
3158 return STF_INTERNAL_ERROR;
3159 }
3160 }
3161
3162 /* if enabled send Cisco Unity Vendor ID */
3163 if (SEND_CISCO_UNITY_VID)
3164 {
3165 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3166 , &md->rbody, VID_CISCO_UNITY))
3167 {
3168 return STF_INTERNAL_ERROR;
3169 }
3170 }
3171
3172 /*
3173 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3174 */
3175 if (md->openpgp)
3176 {
3177 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3178 , &md->rbody, VID_OPENPGP))
3179 {
3180 return STF_INTERNAL_ERROR;
3181 }
3182 }
3183
3184 /* Announce our ability to do eXtended AUTHentication to the peer */
3185 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3186 , &md->rbody, VID_MISC_XAUTH))
3187 {
3188 return STF_INTERNAL_ERROR;
3189 }
3190
3191 /* Announce our ability to do Dead Peer Detection to the peer */
3192 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3193 , &md->rbody, VID_MISC_DPD))
3194 {
3195 return STF_INTERNAL_ERROR;
3196 }
3197
3198 if (md->nat_traversal_vid && nat_traversal_enabled)
3199 {
3200 /* reply if NAT-Traversal draft is supported */
3201 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3202
3203 if (st->nat_traversal
3204 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3205 , &md->rbody, md->nat_traversal_vid))
3206 {
3207 return STF_INTERNAL_ERROR;
3208 }
3209 }
3210
3211 close_message(&md->rbody);
3212
3213 /* save initiator SA for HASH */
3214 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3215
3216 return STF_OK;
3217 }
3218
3219 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3220 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3221 *
3222 * The following are not yet implemented:
3223 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3224 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3225 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3226 *
3227 * We must verify that the proposal received matches one we sent.
3228 */
3229 stf_status
3230 main_inR1_outI2(struct msg_digest *md)
3231 {
3232 struct state *const st = md->st;
3233
3234 u_int8_t np = ISAKMP_NEXT_NONE;
3235
3236 /* verify echoed SA */
3237 {
3238 u_int32_t ipsecdoisit;
3239 pb_stream proposal_pbs;
3240 struct isakmp_proposal proposal;
3241 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3242
3243 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3244 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3245 if (proposal.isap_notrans != 1)
3246 {
3247 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3248 , (unsigned)proposal.isap_notrans);
3249 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX);
3250 }
3251 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3252 , &proposal_pbs, &proposal, NULL, st, TRUE));
3253 }
3254
3255 if (nat_traversal_enabled && md->nat_traversal_vid)
3256 {
3257 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3258 plog("enabling possible NAT-traversal with method %s"
3259 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3260 }
3261 if (st->nat_traversal & NAT_T_WITH_NATD)
3262 {
3263 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3264 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3265 }
3266
3267 /**************** build output packet HDR;KE;Ni ****************/
3268
3269 /* HDR out.
3270 * We can't leave this to comm_handle() because the isa_np
3271 * depends on the type of Auth (eventually).
3272 */
3273 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3274
3275 /* KE out */
3276 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3277 , &md->rbody, ISAKMP_NEXT_NONCE))
3278 return STF_INTERNAL_ERROR;
3279
3280 #ifdef DEBUG
3281 /* Ni out */
3282 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3283 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3284 return STF_INTERNAL_ERROR;
3285
3286 if (cur_debugging & IMPAIR_BUST_MI2)
3287 {
3288 /* generate a pointless large VID payload to push message over MTU */
3289 pb_stream vid_pbs;
3290
3291 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3292 return STF_INTERNAL_ERROR;
3293 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3294 return STF_INTERNAL_ERROR;
3295 close_output_pbs(&vid_pbs);
3296 }
3297 #else
3298 /* Ni out */
3299 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3300 return STF_INTERNAL_ERROR;
3301 #endif
3302
3303 if (st->nat_traversal & NAT_T_WITH_NATD)
3304 {
3305 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3306 return STF_INTERNAL_ERROR;
3307 }
3308
3309 /* finish message */
3310 close_message(&md->rbody);
3311
3312 /* Reinsert the state, using the responder cookie we just received */
3313 unhash_state(st);
3314 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3315 insert_state(st); /* needs cookies, connection, and msgid (0) */
3316
3317 return STF_OK;
3318 }
3319
3320 /* STATE_MAIN_R1:
3321 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3322 *
3323 * The following are not yet implemented:
3324 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3325 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3326 * RPKE_AUTH:
3327 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3328 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3329 */
3330 stf_status
3331 main_inI2_outR2(struct msg_digest *md)
3332 {
3333 struct state *const st = md->st;
3334 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3335
3336 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3337 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3338 || st->st_oakley.auth == XAUTHInitRSA
3339 || st->st_oakley.auth == XAUTHRespRSA;
3340 bool send_cr = !no_cr_send && RSA_auth && !has_preloaded_public_key(st);
3341
3342 u_int8_t np = ISAKMP_NEXT_NONE;
3343
3344 /* KE in */
3345 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3346
3347 /* Ni in */
3348 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3349
3350 if (st->nat_traversal & NAT_T_WITH_NATD)
3351 {
3352 nat_traversal_natd_lookup(md);
3353
3354 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3355 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3356 }
3357 if (st->nat_traversal)
3358 {
3359 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3360 }
3361 if (st->nat_traversal & NAT_T_WITH_KA)
3362 {
3363 nat_traversal_new_ka_event();
3364 }
3365
3366 /* decode certificate requests */
3367 st->st_connection->got_certrequest = FALSE;
3368 decode_cr(md, st->st_connection);
3369
3370 /**************** build output packet HDR;KE;Nr ****************/
3371
3372 /* HDR out done */
3373
3374 /* KE out */
3375 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3376 , &md->rbody, ISAKMP_NEXT_NONCE))
3377 return STF_INTERNAL_ERROR;
3378
3379 #ifdef DEBUG
3380 /* Nr out */
3381 if (!build_and_ship_nonce(&st->st_nr, &md->rbody
3382 , (cur_debugging & IMPAIR_BUST_MR2)? ISAKMP_NEXT_VID
3383 : (send_cr? ISAKMP_NEXT_CR : np), "Nr"))
3384 return STF_INTERNAL_ERROR;
3385
3386 if (cur_debugging & IMPAIR_BUST_MR2)
3387 {
3388 /* generate a pointless large VID payload to push message over MTU */
3389 pb_stream vid_pbs;
3390
3391 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : np,
3392 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3393 return STF_INTERNAL_ERROR;
3394 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3395 return STF_INTERNAL_ERROR;
3396 close_output_pbs(&vid_pbs);
3397 }
3398 #else
3399 /* Nr out */
3400 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3401 (send_cr)? ISAKMP_NEXT_CR : np, "Nr"))
3402 return STF_INTERNAL_ERROR;
3403 #endif
3404
3405 /* CR out */
3406 if (send_cr)
3407 {
3408 if (st->st_connection->kind == CK_PERMANENT)
3409 {
3410 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3411 , st->st_connection->spd.that.ca
3412 , &md->rbody, np))
3413 return STF_INTERNAL_ERROR;
3414 }
3415 else
3416 {
3417 generalName_t *ca = NULL;
3418
3419 if (collect_rw_ca_candidates(md, &ca))
3420 {
3421 generalName_t *gn;
3422
3423 for (gn = ca; gn != NULL; gn = gn->next)
3424 {
3425 if (!build_and_ship_CR(CERT_X509_SIGNATURE, gn->name
3426 , &md->rbody
3427 , gn->next == NULL ? np : ISAKMP_NEXT_CR))
3428 return STF_INTERNAL_ERROR;
3429 }
3430 free_generalNames(ca, FALSE);
3431 }
3432 else
3433 {
3434 if (!build_and_ship_CR(CERT_X509_SIGNATURE, empty_chunk
3435 , &md->rbody, np))
3436 return STF_INTERNAL_ERROR;
3437 }
3438 }
3439 }
3440
3441 if (st->nat_traversal & NAT_T_WITH_NATD)
3442 {
3443 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3444 return STF_INTERNAL_ERROR;
3445 }
3446
3447 /* finish message */
3448 close_message(&md->rbody);
3449
3450 /* next message will be encrypted, but not this one.
3451 * We could defer this calculation.
3452 */
3453 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3454 if (!generate_skeyids_iv(st))
3455 return STF_FAIL + AUTHENTICATION_FAILED;
3456 update_iv(st);
3457
3458 return STF_OK;
3459 }
3460
3461 /* STATE_MAIN_I2:
3462 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3463 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3464 *
3465 * The following are not yet implemented.
3466 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3467 * --> HDR*, HASH_I
3468 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3469 * --> HDR*, HASH_I
3470 */
3471 stf_status
3472 main_inR2_outI3(struct msg_digest *md)
3473 {
3474 struct state *const st = md->st;
3475 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3476 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3477
3478 certpolicy_t cert_policy = st->st_connection->spd.this.sendcert;
3479 cert_t mycert = st->st_connection->spd.this.cert;
3480 bool requested, send_cert, send_cr;
3481
3482 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3483 || st->st_oakley.auth == XAUTHInitRSA
3484 || st->st_oakley.auth == XAUTHRespRSA;
3485
3486 int auth_payload = RSA_auth ? ISAKMP_NEXT_SIG : ISAKMP_NEXT_HASH;
3487
3488 /* KE in */
3489 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3490
3491 /* Nr in */
3492 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3493
3494 /* decode certificate requests */
3495 st->st_connection->got_certrequest = FALSE;
3496 decode_cr(md, st->st_connection);
3497
3498 /* free collected certificate requests since as initiator
3499 * we don't heed them anyway
3500 */
3501 free_generalNames(st->st_connection->requested_ca, TRUE);
3502 st->st_connection->requested_ca = NULL;
3503
3504 /* send certificate if auth is RSA, we have one and we want
3505 * or are requested to send it
3506 */
3507 requested = cert_policy == CERT_SEND_IF_ASKED
3508 && st->st_connection->got_certrequest;
3509 send_cert = RSA_auth && mycert.type != CERT_NONE
3510 && (cert_policy == CERT_ALWAYS_SEND || requested);
3511
3512 /* send certificate request if we don't have a preloaded RSA public key */
3513 send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3514
3515 /* done parsing; initialize crypto */
3516 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3517 if (!generate_skeyids_iv(st))
3518 return STF_FAIL + AUTHENTICATION_FAILED;
3519
3520 if (st->nat_traversal & NAT_T_WITH_NATD)
3521 {
3522 nat_traversal_natd_lookup(md);
3523 }
3524 if (st->nat_traversal)
3525 {
3526 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3527 }
3528 if (st->nat_traversal & NAT_T_WITH_KA)
3529 {
3530 nat_traversal_new_ka_event();
3531 }
3532
3533 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3534 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3535
3536 /* HDR* out done */
3537
3538 /* IDii out */
3539 {
3540 struct isakmp_ipsec_id id_hd;
3541 chunk_t id_b;
3542
3543 build_id_payload(&id_hd, &id_b, &st->st_connection->spd.this);
3544 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3545 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3546 || !out_chunk(id_b, &id_pbs, "my identity"))
3547 return STF_INTERNAL_ERROR;
3548 close_output_pbs(&id_pbs);
3549 }
3550
3551 /* CERT out */
3552 if (RSA_auth)
3553 {
3554 DBG(DBG_CONTROL,
3555 DBG_log("our certificate policy is %s"
3556 , enum_name(&cert_policy_names, cert_policy))
3557 )
3558 if (mycert.type != CERT_NONE)
3559 {
3560 const char *request_text = "";
3561
3562 if (cert_policy == CERT_SEND_IF_ASKED)
3563 request_text = (send_cert)? "upon request":"without request";
3564 plog("we have a cert %s sending it %s"
3565 , send_cert? "and are":"but are not", request_text);
3566 }
3567 else
3568 {
3569 plog("we don't have a cert");
3570 }
3571 }
3572 if (send_cert)
3573 {
3574 pb_stream cert_pbs;
3575
3576 struct isakmp_cert cert_hd;
3577 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3578 cert_hd.isacert_type = mycert.type;
3579
3580 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3581 return STF_INTERNAL_ERROR;
3582 if (!out_chunk(get_mycert(mycert), &cert_pbs, "CERT"))
3583 return STF_INTERNAL_ERROR;
3584 close_output_pbs(&cert_pbs);
3585 }
3586
3587 /* CR out */
3588 if (send_cr)
3589 {
3590 if (!build_and_ship_CR(mycert.type, st->st_connection->spd.that.ca
3591 , &md->rbody, ISAKMP_NEXT_SIG))
3592 return STF_INTERNAL_ERROR;
3593 }
3594
3595 /* HASH_I or SIG_I out */
3596 {
3597 u_char hash_val[MAX_DIGEST_LEN];
3598 size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3599
3600 if (auth_payload == ISAKMP_NEXT_HASH)
3601 {
3602 /* HASH_I out */
3603 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3604 , hash_val, hash_len, "HASH_I"))
3605 return STF_INTERNAL_ERROR;
3606 }
3607 else
3608 {
3609 /* SIG_I out */
3610 u_char sig_val[RSA_MAX_OCTETS];
3611 size_t sig_len = RSA_sign_hash(st->st_connection
3612 , sig_val, hash_val, hash_len);
3613
3614 if (sig_len == 0)
3615 {
3616 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3617 return STF_FAIL + AUTHENTICATION_FAILED;
3618 }
3619
3620 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3621 , &md->rbody, sig_val, sig_len, "SIG_I"))
3622 return STF_INTERNAL_ERROR;
3623 }
3624 }
3625
3626 /* encrypt message, except for fixed part of header */
3627
3628 /* st_new_iv was computed by generate_skeyids_iv */
3629 if (!encrypt_message(&md->rbody, st))
3630 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3631
3632 return STF_OK;
3633 }
3634
3635 /* Shared logic for asynchronous lookup of DNS KEY records.
3636 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3637 */
3638
3639 enum key_oppo_step {
3640 kos_null,
3641 kos_his_txt
3642 #ifdef USE_KEYRR
3643 , kos_his_key
3644 #endif
3645 };
3646
3647 struct key_continuation {
3648 struct adns_continuation ac; /* common prefix */
3649 struct msg_digest *md;
3650 enum key_oppo_step step;
3651 bool failure_ok;
3652 err_t last_ugh;
3653 };
3654
3655 typedef stf_status (key_tail_fn)(struct msg_digest *md
3656 , struct key_continuation *kc);
3657 static void
3658 report_key_dns_failure(struct id *id, err_t ugh)
3659 {
3660 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
3661
3662 (void) idtoa(id, id_buf, sizeof(id_buf));
3663 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3664 "; DNS search for KEY failed (%s)", id_buf, ugh);
3665 }
3666
3667
3668 /* Processs the Main Mode ID Payload and the Authenticator
3669 * (Hash or Signature Payload).
3670 * If a DNS query is still needed to get the other host's public key,
3671 * the query is initiated and STF_SUSPEND is returned.
3672 * Note: parameter kc is a continuation containing the results from
3673 * the previous DNS query, or NULL indicating no query has been issued.
3674 */
3675 static stf_status
3676 main_id_and_auth(struct msg_digest *md
3677 , bool initiator /* are we the Initiator? */
3678 , cont_fn_t cont_fn /* continuation function */
3679 , const struct key_continuation *kc /* current state, can be NULL */
3680 )
3681 {
3682 struct state *st = md->st;
3683 u_char hash_val[MAX_DIGEST_LEN];
3684 size_t hash_len;
3685 struct id peer;
3686 stf_status r = STF_OK;
3687
3688 /* ID Payload in */
3689 if (!decode_peer_id(md, &peer))
3690 return STF_FAIL + INVALID_ID_INFORMATION;
3691
3692 /* Hash the ID Payload.
3693 * main_mode_hash requires idpl->cur to be at end of payload
3694 * so we temporarily set if so.
3695 */
3696 {
3697 pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3698 u_int8_t *old_cur = idpl->cur;
3699
3700 idpl->cur = idpl->roof;
3701 hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3702 idpl->cur = old_cur;
3703 }
3704
3705 switch (st->st_oakley.auth)
3706 {
3707 case OAKLEY_PRESHARED_KEY:
3708 case XAUTHInitPreShared:
3709 case XAUTHRespPreShared:
3710 {
3711 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3712
3713 if (pbs_left(hash_pbs) != hash_len
3714 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3715 {
3716 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3717 , hash_pbs->cur, pbs_left(hash_pbs));
3718 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3719 /* XXX Could send notification back */
3720 r = STF_FAIL + INVALID_HASH_INFORMATION;
3721 }
3722 }
3723 break;
3724
3725 case OAKLEY_RSA_SIG:
3726 case XAUTHInitRSA:
3727 case XAUTHRespRSA:
3728 r = RSA_check_signature(&peer, st, hash_val, hash_len
3729 , &md->chain[ISAKMP_NEXT_SIG]->pbs
3730 #ifdef USE_KEYRR
3731 , kc == NULL? NULL : kc->ac.keys_from_dns
3732 #endif /* USE_KEYRR */
3733 , kc == NULL? NULL : kc->ac.gateways_from_dns
3734 );
3735
3736 if (r == STF_SUSPEND)
3737 {
3738 /* initiate/resume asynchronous DNS lookup for key */
3739 struct key_continuation *nkc
3740 = alloc_thing(struct key_continuation, "key continuation");
3741 enum key_oppo_step step_done = kc == NULL? kos_null : kc->step;
3742 err_t ugh;
3743
3744 /* Record that state is used by a suspended md */
3745 passert(st->st_suspended_md == NULL);
3746 st->st_suspended_md = md;
3747
3748 nkc->failure_ok = FALSE;
3749 nkc->md = md;
3750
3751 switch (step_done)
3752 {
3753 case kos_null:
3754 /* first try: look for the TXT records */
3755 nkc->step = kos_his_txt;
3756 #ifdef USE_KEYRR
3757 nkc->failure_ok = TRUE;
3758 #endif
3759 ugh = start_adns_query(&peer
3760 , &peer /* SG itself */
3761 , T_TXT
3762 , cont_fn
3763 , &nkc->ac);
3764 break;
3765
3766 #ifdef USE_KEYRR
3767 case kos_his_txt:
3768 /* second try: look for the KEY records */
3769 nkc->step = kos_his_key;
3770 ugh = start_adns_query(&peer
3771 , NULL /* no sgw for KEY */
3772 , T_KEY
3773 , cont_fn
3774 , &nkc->ac);
3775 break;
3776 #endif /* USE_KEYRR */
3777
3778 default:
3779 bad_case(step_done);
3780 }
3781
3782 if (ugh != NULL)
3783 {
3784 report_key_dns_failure(&peer, ugh);
3785 st->st_suspended_md = NULL;
3786 r = STF_FAIL + INVALID_KEY_INFORMATION;
3787 }
3788 }
3789 break;
3790
3791 default:
3792 bad_case(st->st_oakley.auth);
3793 }
3794 if (r != STF_OK