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