fixed all pluto compiler warnings
[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), val_name);
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, alloc_bytes(DEFAULT_NONCE_SIZE, name), 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 = alloc_thing(generalName_t, "generalName");
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 , "sa in main_outI1");
967 }
968
969 /* if enabled send Pluto Vendor ID */
970 if (SEND_PLUTO_VID)
971 {
972 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
973 , &rbody, VID_STRONGSWAN))
974 {
975 reset_cur_state();
976 return STF_INTERNAL_ERROR;
977 }
978 }
979
980 /* if enabled send Cisco Unity Vendor ID */
981 if (SEND_CISCO_UNITY_VID)
982 {
983 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
984 , &rbody, VID_CISCO_UNITY))
985 {
986 reset_cur_state();
987 return STF_INTERNAL_ERROR;
988 }
989 }
990 /* if we have an OpenPGP certificate we assume an
991 * OpenPGP peer and have to send the Vendor ID
992 */
993 if (c->spd.this.cert.type == CERT_PGP)
994 {
995 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
996 , &rbody, VID_OPENPGP))
997 {
998 reset_cur_state();
999 return STF_INTERNAL_ERROR;
1000 }
1001 }
1002
1003 /* Announce our ability to do eXtended AUTHentication to the peer */
1004 if (SEND_XAUTH_VID)
1005 {
1006 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1007 , &rbody, VID_MISC_XAUTH))
1008 {
1009 reset_cur_state();
1010 return STF_INTERNAL_ERROR;
1011 }
1012 }
1013
1014 /* Announce our ability to do Dead Peer Detection to the peer */
1015 {
1016 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1017 , &rbody, VID_MISC_DPD))
1018 {
1019 reset_cur_state();
1020 return STF_INTERNAL_ERROR;
1021 }
1022 }
1023
1024 if (nat_traversal_enabled)
1025 {
1026 /* Add supported NAT-Traversal VID */
1027 if (!nat_traversal_add_vid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1028 , &rbody))
1029 {
1030 reset_cur_state();
1031 return STF_INTERNAL_ERROR;
1032 }
1033 }
1034
1035 close_message(&rbody);
1036 close_output_pbs(&reply);
1037
1038 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
1039 , "reply packet for main_outI1");
1040
1041 /* Transmit */
1042
1043 send_packet(st, "main_outI1");
1044
1045 /* Set up a retransmission event, half a minute henceforth */
1046 delete_event(st);
1047 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1048
1049 if (predecessor != NULL)
1050 {
1051 update_pending(predecessor, st);
1052 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1053 , "%s: initiate, replacing #%lu"
1054 , enum_name(&state_names, st->st_state)
1055 , predecessor->st_serialno);
1056 }
1057 else
1058 {
1059 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1060 , "%s: initiate", enum_name(&state_names, st->st_state));
1061 }
1062 reset_cur_state();
1063 return STF_OK;
1064 }
1065
1066 void
1067 ipsecdoi_initiate(int whack_sock
1068 , struct connection *c
1069 , lset_t policy
1070 , unsigned long try
1071 , so_serial_t replacing)
1072 {
1073 /* If there's already an ISAKMP SA established, use that and
1074 * go directly to Quick Mode. We are even willing to use one
1075 * that is still being negotiated, but only if we are the Initiator
1076 * (thus we can be sure that the IDs are not going to change;
1077 * other issues around intent might matter).
1078 * Note: there is no way to initiate with a Road Warrior.
1079 */
1080 struct state *st = find_phase1_state(c
1081 , ISAKMP_SA_ESTABLISHED_STATES | PHASE1_INITIATOR_STATES);
1082
1083 if (st == NULL)
1084 {
1085 (void) main_outI1(whack_sock, c, NULL, policy, try);
1086 }
1087 else if (HAS_IPSEC_POLICY(policy))
1088 {
1089 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1090 {
1091 /* leave our Phase 2 negotiation pending */
1092 add_pending(whack_sock, st, c, policy, try, replacing);
1093 }
1094 else
1095 {
1096 /* ??? we assume that peer_nexthop_sin isn't important:
1097 * we already have it from when we negotiated the ISAKMP SA!
1098 * It isn't clear what to do with the error return.
1099 */
1100 (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1101 }
1102 }
1103 else
1104 {
1105 close_any(whack_sock);
1106 }
1107 }
1108
1109 /* Replace SA with a fresh one that is similar
1110 *
1111 * Shares some logic with ipsecdoi_initiate, but not the same!
1112 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1113 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1114 * ISAKMP SA if needed.
1115 * - duplicate whack fd, if live.
1116 * Does not delete the old state -- someone else will do that.
1117 */
1118 void
1119 ipsecdoi_replace(struct state *st, unsigned long try)
1120 {
1121 int whack_sock = dup_any(st->st_whack_sock);
1122 lset_t policy = st->st_policy;
1123
1124 if (IS_PHASE1(st->st_state))
1125 {
1126 passert(!HAS_IPSEC_POLICY(policy));
1127 (void) main_outI1(whack_sock, st->st_connection, st, policy, try);
1128 }
1129 else
1130 {
1131 /* Add features of actual old state to policy. This ensures
1132 * that rekeying doesn't downgrade security. I admit that
1133 * this doesn't capture everything.
1134 */
1135 if (st->st_pfs_group != NULL)
1136 policy |= POLICY_PFS;
1137 if (st->st_ah.present)
1138 {
1139 policy |= POLICY_AUTHENTICATE;
1140 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1141 policy |= POLICY_TUNNEL;
1142 }
1143 if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1144 {
1145 policy |= POLICY_ENCRYPT;
1146 if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1147 policy |= POLICY_TUNNEL;
1148 }
1149 if (st->st_ipcomp.present)
1150 {
1151 policy |= POLICY_COMPRESS;
1152 if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1153 policy |= POLICY_TUNNEL;
1154 }
1155 passert(HAS_IPSEC_POLICY(policy));
1156 ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1157 , st->st_serialno);
1158 }
1159 }
1160
1161 /* SKEYID for preshared keys.
1162 * See draft-ietf-ipsec-ike-01.txt 4.1
1163 */
1164 static bool
1165 skeyid_preshared(struct state *st)
1166 {
1167 const chunk_t *pss = get_preshared_secret(st->st_connection);
1168
1169 if (pss == NULL)
1170 {
1171 loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1172 return FALSE;
1173 }
1174 else
1175 {
1176 struct hmac_ctx ctx;
1177
1178 hmac_init_chunk(&ctx, st->st_oakley.hasher, *pss);
1179 hmac_update_chunk(&ctx, st->st_ni);
1180 hmac_update_chunk(&ctx, st->st_nr);
1181 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_preshared()", &ctx);
1182 return TRUE;
1183 }
1184 }
1185
1186 static bool
1187 skeyid_digisig(struct state *st)
1188 {
1189 struct hmac_ctx ctx;
1190 chunk_t nir;
1191
1192 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1193 * so we have to build a temporary concatentation.
1194 */
1195 nir.len = st->st_ni.len + st->st_nr.len;
1196 nir.ptr = alloc_bytes(nir.len, "Ni + Nr in skeyid_digisig");
1197 memcpy(nir.ptr, st->st_ni.ptr, st->st_ni.len);
1198 memcpy(nir.ptr+st->st_ni.len, st->st_nr.ptr, st->st_nr.len);
1199 hmac_init_chunk(&ctx, st->st_oakley.hasher, nir);
1200 pfree(nir.ptr);
1201
1202 hmac_update_chunk(&ctx, st->st_shared);
1203 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_digisig()", &ctx);
1204 return TRUE;
1205 }
1206
1207 /* Generate the SKEYID_* and new IV
1208 * See draft-ietf-ipsec-ike-01.txt 4.1
1209 */
1210 static bool
1211 generate_skeyids_iv(struct state *st)
1212 {
1213 /* Generate the SKEYID */
1214 switch (st->st_oakley.auth)
1215 {
1216 case OAKLEY_PRESHARED_KEY:
1217 case XAUTHInitPreShared:
1218 case XAUTHRespPreShared:
1219 if (!skeyid_preshared(st))
1220 return FALSE;
1221 break;
1222
1223 case OAKLEY_RSA_SIG:
1224 case XAUTHInitRSA:
1225 case XAUTHRespRSA:
1226 if (!skeyid_digisig(st))
1227 return FALSE;
1228 break;
1229
1230 case OAKLEY_DSS_SIG:
1231 /* XXX */
1232
1233 case OAKLEY_RSA_ENC:
1234 case OAKLEY_RSA_ENC_REV:
1235 case OAKLEY_ELGAMAL_ENC:
1236 case OAKLEY_ELGAMAL_ENC_REV:
1237 /* XXX */
1238
1239 default:
1240 bad_case(st->st_oakley.auth);
1241 }
1242
1243 /* generate SKEYID_* from SKEYID */
1244 {
1245 struct hmac_ctx ctx;
1246
1247 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1248
1249 /* SKEYID_D */
1250 hmac_update_chunk(&ctx, st->st_shared);
1251 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1252 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1253 hmac_update(&ctx, "\0", 1);
1254 hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1255
1256 /* SKEYID_A */
1257 hmac_reinit(&ctx);
1258 hmac_update_chunk(&ctx, st->st_skeyid_d);
1259 hmac_update_chunk(&ctx, st->st_shared);
1260 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1261 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1262 hmac_update(&ctx, "\1", 1);
1263 hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1264
1265 /* SKEYID_E */
1266 hmac_reinit(&ctx);
1267 hmac_update_chunk(&ctx, st->st_skeyid_a);
1268 hmac_update_chunk(&ctx, st->st_shared);
1269 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1270 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1271 hmac_update(&ctx, "\2", 1);
1272 hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1273 }
1274
1275 /* generate IV */
1276 {
1277 union hash_ctx hash_ctx;
1278 const struct hash_desc *h = st->st_oakley.hasher;
1279
1280 st->st_new_iv_len = h->hash_digest_size;
1281 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1282
1283 DBG(DBG_CRYPT,
1284 DBG_dump_chunk("DH_i:", st->st_gi);
1285 DBG_dump_chunk("DH_r:", st->st_gr);
1286 );
1287 h->hash_init(&hash_ctx);
1288 h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1289 h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1290 h->hash_final(st->st_new_iv, &hash_ctx);
1291 }
1292
1293 /* Oakley Keying Material
1294 * Derived from Skeyid_e: if it is not big enough, generate more
1295 * using the PRF.
1296 * See RFC 2409 "IKE" Appendix B
1297 */
1298 {
1299 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1300 const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1301 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1302 u_char *k = st->st_skeyid_e.ptr;
1303
1304 if (keysize > st->st_skeyid_e.len)
1305 {
1306 struct hmac_ctx ctx;
1307 size_t i = 0;
1308
1309 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1310 hmac_update(&ctx, "\0", 1);
1311 for (;;)
1312 {
1313 hmac_final(&keytemp[i], &ctx);
1314 i += ctx.hmac_digest_size;
1315 if (i >= keysize)
1316 break;
1317 hmac_reinit(&ctx);
1318 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1319 }
1320 k = keytemp;
1321 }
1322 clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1323 }
1324
1325 DBG(DBG_CRYPT,
1326 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1327 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1328 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1329 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1330 DBG_dump_chunk("enc key:", st->st_enc_key);
1331 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1332 return TRUE;
1333 }
1334
1335 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1336 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1337 * New Group Mode, or ISAKMP Informational Exchanges).
1338 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1339 * If hashus argument is TRUE, we're generating a hash for our end.
1340 * See RFC2409 IKE 5.
1341 *
1342 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1343 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1344 * The extensive common logic is embodied in main_mode_hash_body().
1345 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1346 */
1347
1348 typedef void (*hash_update_t)(union hash_ctx *, const u_char *, size_t) ;
1349 static void
1350 main_mode_hash_body(struct state *st
1351 , bool hashi /* Initiator? */
1352 , const pb_stream *idpl /* ID payload, as PBS */
1353 , union hash_ctx *ctx
1354 , void (*hash_update_void)(void *, const u_char *input, size_t))
1355 {
1356 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1357 hash_update_t hash_update=(hash_update_t) hash_update_void;
1358 #if 0 /* if desperate to debug hashing */
1359 # define hash_update(ctx, input, len) { \
1360 DBG_dump("hash input", input, len); \
1361 (hash_update)(ctx, input, len); \
1362 }
1363 #endif
1364
1365 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1366
1367 if (hashi)
1368 {
1369 hash_update_chunk(ctx, st->st_gi);
1370 hash_update_chunk(ctx, st->st_gr);
1371 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1372 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1373 }
1374 else
1375 {
1376 hash_update_chunk(ctx, st->st_gr);
1377 hash_update_chunk(ctx, st->st_gi);
1378 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1379 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1380 }
1381
1382 DBG(DBG_CRYPT, DBG_log("hashing %lu bytes of SA"
1383 , (unsigned long) (st->st_p1isa.len - sizeof(struct isakmp_generic))));
1384
1385 /* SA_b */
1386 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1387 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1388
1389 /* Hash identification payload, without generic payload header.
1390 * We used to reconstruct ID Payload for this purpose, but now
1391 * we use the bytes as they appear on the wire to avoid
1392 * "spelling problems".
1393 */
1394 hash_update(ctx
1395 , idpl->start + sizeof(struct isakmp_generic)
1396 , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1397
1398 # undef hash_update_chunk
1399 # undef hash_update
1400 }
1401
1402 static size_t /* length of hash */
1403 main_mode_hash(struct state *st
1404 , u_char *hash_val /* resulting bytes */
1405 , bool hashi /* Initiator? */
1406 , const pb_stream *idpl) /* ID payload, as PBS; cur must be at end */
1407 {
1408 struct hmac_ctx ctx;
1409
1410 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1411 main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1412 hmac_final(hash_val, &ctx);
1413 return ctx.hmac_digest_size;
1414 }
1415
1416 #if 0 /* only needed for DSS */
1417 static void
1418 main_mode_sha1(struct state *st
1419 , u_char *hash_val /* resulting bytes */
1420 , size_t *hash_len /* length of hash */
1421 , bool hashi /* Initiator? */
1422 , const pb_stream *idpl) /* ID payload, as PBS */
1423 {
1424 union hash_ctx ctx;
1425
1426 SHA1Init(&ctx.ctx_sha1);
1427 SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1428 *hash_len = SHA1_DIGEST_SIZE;
1429 main_mode_hash_body(st, hashi, idpl, &ctx
1430 , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1431 SHA1Final(hash_val, &ctx.ctx_sha1);
1432 }
1433 #endif
1434
1435 /* Create an RSA signature of a hash.
1436 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1437 * Use PKCS#1 version 1.5 encryption of hash (called
1438 * RSAES-PKCS1-V1_5) in PKCS#2.
1439 */
1440 static size_t
1441 RSA_sign_hash(struct connection *c
1442 , u_char sig_val[RSA_MAX_OCTETS]
1443 , const u_char *hash_val, size_t hash_len)
1444 {
1445 size_t sz = 0;
1446 smartcard_t *sc = c->spd.this.sc;
1447
1448 if (sc == NULL) /* no smartcard */
1449 {
1450 const struct RSA_private_key *k = get_RSA_private_key(c);
1451
1452 if (k == NULL)
1453 return 0; /* failure: no key to use */
1454
1455 sz = k->pub.k;
1456 passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1457 sign_hash(k, hash_val, hash_len, sig_val, sz);
1458 }
1459 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1460 {
1461 lock_certs_and_keys("RSA_sign_hash");
1462 if (!scx_establish_context(sc) || !scx_login(sc))
1463 {
1464 scx_release_context(sc);
1465 unlock_certs_and_keys("RSA_sign_hash");
1466 return 0;
1467 }
1468
1469 sz = scx_get_keylength(sc);
1470 if (sz == 0)
1471 {
1472 plog("failed to get keylength from smartcard");
1473 scx_release_context(sc);
1474 unlock_certs_and_keys("RSA_sign_hash");
1475 return 0;
1476 }
1477
1478 DBG(DBG_CONTROL | DBG_CRYPT,
1479 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1480 , (int)sc->slot, sc->id)
1481 )
1482 sz = scx_sign_hash(sc, hash_val, hash_len, sig_val, sz) ? sz : 0;
1483 if (!pkcs11_keep_state)
1484 scx_release_context(sc);
1485 unlock_certs_and_keys("RSA_sign_hash");
1486 }
1487 return sz;
1488 }
1489
1490 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1491 *
1492 * As a side effect, on success, the public key is copied into the
1493 * state object to record the authenticator.
1494 *
1495 * Can fail because wrong public key is used or because hash disagrees.
1496 * We distinguish because diagnostics should also.
1497 *
1498 * The result is NULL if the Signature checked out.
1499 * Otherwise, the first character of the result indicates
1500 * how far along failure occurred. A greater character signifies
1501 * greater progress.
1502 *
1503 * Classes:
1504 * 0 reserved for caller
1505 * 1 SIG length doesn't match key length -- wrong key
1506 * 2-8 malformed ECB after decryption -- probably wrong key
1507 * 9 decrypted hash != computed hash -- probably correct key
1508 *
1509 * Although the math should be the same for generating and checking signatures,
1510 * it is not: the knowledge of the private key allows more efficient (i.e.
1511 * different) computation for encryption.
1512 */
1513 static err_t
1514 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1515 , const pb_stream *sig_pbs, pubkey_t *kr
1516 , struct state *st)
1517 {
1518 const u_char *sig_val = sig_pbs->cur;
1519 size_t sig_len = pbs_left(sig_pbs);
1520 u_char s[RSA_MAX_OCTETS]; /* for decrypted sig_val */
1521 u_char *hash_in_s = &s[sig_len - hash_len];
1522 const struct RSA_public_key *k = &kr->u.rsa;
1523
1524 /* decrypt the signature -- reversing RSA_sign_hash */
1525 if (sig_len != k->k)
1526 {
1527 /* XXX notification: INVALID_KEY_INFORMATION */
1528 return "1" "SIG length does not match public key length";
1529 }
1530
1531 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1532 {
1533 chunk_t temp_s;
1534 mpz_t c;
1535
1536 n_to_mpz(c, sig_val, sig_len);
1537 mpz_powm(c, c, &k->e, &k->n);
1538
1539 temp_s = mpz_to_n(c, sig_len); /* back to octets */
1540 memcpy(s, temp_s.ptr, sig_len);
1541 pfree(temp_s.ptr);
1542 mpz_clear(c);
1543 }
1544
1545 /* sanity check on signature: see if it matches
1546 * PKCS#1 v1.5 8.1 encryption-block formatting
1547 */
1548 {
1549 err_t ugh = NULL;
1550
1551 if (s[0] != 0x00)
1552 ugh = "2" "no leading 00";
1553 else if (hash_in_s[-1] != 0x00)
1554 ugh = "3" "00 separator not present";
1555 else if (s[1] == 0x01)
1556 {
1557 const u_char *p;
1558
1559 for (p = &s[2]; p != hash_in_s - 1; p++)
1560 {
1561 if (*p != 0xFF)
1562 {
1563 ugh = "4" "invalid Padding String";
1564 break;
1565 }
1566 }
1567 }
1568 else if (s[1] == 0x02)
1569 {
1570 const u_char *p;
1571
1572 for (p = &s[2]; p != hash_in_s - 1; p++)
1573 {
1574 if (*p == 0x00)
1575 {
1576 ugh = "5" "invalid Padding String";
1577 break;
1578 }
1579 }
1580 }
1581 else
1582 ugh = "6" "Block Type not 01 or 02";
1583
1584 if (ugh != NULL)
1585 {
1586 /* note: it might be a good idea to make sure that
1587 * an observer cannot tell what kind of failure happened.
1588 * I don't know what this means in practice.
1589 */
1590 /* We probably selected the wrong public key for peer:
1591 * SIG Payload decrypted into malformed ECB
1592 */
1593 /* XXX notification: INVALID_KEY_INFORMATION */
1594 return ugh;
1595 }
1596 }
1597
1598 /* We have the decoded hash: see if it matches. */
1599 if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1600 {
1601 /* good: header, hash, signature, and other payloads well-formed
1602 * good: we could find an RSA Sig key for the peer.
1603 * bad: hash doesn't match
1604 * Guess: sides disagree about key to be used.
1605 */
1606 DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1607 DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1608 /* XXX notification: INVALID_HASH_INFORMATION */
1609 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1610 }
1611
1612 /* Success: copy successful key into state.
1613 * There might be an old one if we previously aborted this
1614 * state transition.
1615 */
1616 unreference_key(&st->st_peer_pubkey);
1617 st->st_peer_pubkey = reference_key(kr);
1618
1619 return NULL; /* happy happy */
1620 }
1621
1622 /* Check signature against all RSA public keys we can find.
1623 * If we need keys from DNS KEY records, and they haven't been fetched,
1624 * return STF_SUSPEND to ask for asynch DNS lookup.
1625 *
1626 * Note: parameter keys_from_dns contains results of DNS lookup for key
1627 * or is NULL indicating lookup not yet tried.
1628 *
1629 * take_a_crack is a helper function. Mostly forensic.
1630 * If only we had coroutines.
1631 */
1632 struct tac_state {
1633 /* RSA_check_signature's args that take_a_crack needs */
1634 struct state *st;
1635 const u_char *hash_val;
1636 size_t hash_len;
1637 const pb_stream *sig_pbs;
1638
1639 /* state carried between calls */
1640 err_t best_ugh; /* most successful failure */
1641 int tried_cnt; /* number of keys tried */
1642 char tried[50]; /* keyids of tried public keys */
1643 char *tn; /* roof of tried[] */
1644 };
1645
1646 static bool
1647 take_a_crack(struct tac_state *s
1648 , pubkey_t *kr
1649 , const char *story USED_BY_DEBUG)
1650 {
1651 err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1652 , kr, s->st);
1653 const struct RSA_public_key *k = &kr->u.rsa;
1654
1655 s->tried_cnt++;
1656 if (ugh == NULL)
1657 {
1658 DBG(DBG_CRYPT | DBG_CONTROL
1659 , DBG_log("an RSA Sig check passed with *%s [%s]"
1660 , k->keyid, story));
1661 return TRUE;
1662 }
1663 else
1664 {
1665 DBG(DBG_CRYPT
1666 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1667 , ugh + 1, k->keyid, story));
1668 if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1669 s->best_ugh = ugh;
1670 if (ugh[0] > '0'
1671 && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1672 {
1673 strcpy(s->tn, " *");
1674 strcpy(s->tn + 2, k->keyid);
1675 s->tn += strlen(s->tn);
1676 }
1677 return FALSE;
1678 }
1679 }
1680
1681 static stf_status
1682 RSA_check_signature(const struct id* peer
1683 , struct state *st
1684 , const u_char hash_val[MAX_DIGEST_LEN]
1685 , size_t hash_len
1686 , const pb_stream *sig_pbs
1687 #ifdef USE_KEYRR
1688 , const pubkey_list_t *keys_from_dns
1689 #endif /* USE_KEYRR */
1690 , const struct gw_info *gateways_from_dns
1691 )
1692 {
1693 const struct connection *c = st->st_connection;
1694 struct tac_state s;
1695 err_t dns_ugh = NULL;
1696
1697 s.st = st;
1698 s.hash_val = hash_val;
1699 s.hash_len = hash_len;
1700 s.sig_pbs = sig_pbs;
1701
1702 s.best_ugh = NULL;
1703 s.tried_cnt = 0;
1704 s.tn = s.tried;
1705
1706 /* try all gateway records hung off c */
1707 if (c->policy & POLICY_OPPO)
1708 {
1709 struct gw_info *gw;
1710
1711 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1712 {
1713 /* only consider entries that have a key and are for our peer */
1714 if (gw->gw_key_present
1715 && same_id(&gw->gw_id, &c->spd.that.id)
1716 && take_a_crack(&s, gw->key, "key saved from DNS TXT"))
1717 return STF_OK;
1718 }
1719 }
1720
1721 /* try all appropriate Public keys */
1722 {
1723 pubkey_list_t *p, **pp;
1724
1725 pp = &pubkeys;
1726
1727 for (p = pubkeys; p != NULL; p = *pp)
1728 {
1729 pubkey_t *key = p->key;
1730
1731 if (key->alg == PUBKEY_ALG_RSA && same_id(peer, &key->id))
1732 {
1733 time_t now = time(NULL);
1734
1735 /* check if found public key has expired */
1736 if (key->until_time != UNDEFINED_TIME && key->until_time < now)
1737 {
1738 loglog(RC_LOG_SERIOUS,
1739 "cached RSA public key has expired and has been deleted");
1740 *pp = free_public_keyentry(p);
1741 continue; /* continue with next public key */
1742 }
1743
1744 if (take_a_crack(&s, key, "preloaded key"))
1745 return STF_OK;
1746 }
1747 pp = &p->next;
1748 }
1749 }
1750
1751 /* if no key was found (evidenced by best_ugh == NULL)
1752 * and that side of connection is key_from_DNS_on_demand
1753 * then go search DNS for keys for peer.
1754 */
1755 if (s.best_ugh == NULL && c->spd.that.key_from_DNS_on_demand)
1756 {
1757 if (gateways_from_dns != NULL)
1758 {
1759 /* TXT keys */
1760 const struct gw_info *gwp;
1761
1762 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1763 if (gwp->gw_key_present
1764 && take_a_crack(&s, gwp->key, "key from DNS TXT"))
1765 return STF_OK;
1766 }
1767 #ifdef USE_KEYRR
1768 else if (keys_from_dns != NULL)
1769 {
1770 /* KEY keys */
1771 const pubkey_list_t *kr;
1772
1773 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1774 if (kr->key->alg == PUBKEY_ALG_RSA
1775 && take_a_crack(&s, kr->key, "key from DNS KEY"))
1776 return STF_OK;
1777 }
1778 #endif /* USE_KEYRR */
1779 else
1780 {
1781 /* nothing yet: ask for asynch DNS lookup */
1782 return STF_SUSPEND;
1783 }
1784 }
1785
1786 /* no acceptable key was found: diagnose */
1787 {
1788 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
1789
1790 (void) idtoa(peer, id_buf, sizeof(id_buf));
1791
1792 if (s.best_ugh == NULL)
1793 {
1794 if (dns_ugh == NULL)
1795 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1796 , id_buf);
1797 else
1798 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1799 "; DNS search for KEY failed (%s)"
1800 , id_buf, dns_ugh);
1801
1802 /* ??? is this the best code there is? */
1803 return STF_FAIL + INVALID_KEY_INFORMATION;
1804 }
1805
1806 if (s.best_ugh[0] == '9')
1807 {
1808 loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1809 /* XXX Could send notification back */
1810 return STF_FAIL + INVALID_HASH_INFORMATION;
1811 }
1812 else
1813 {
1814 if (s.tried_cnt == 1)
1815 {
1816 loglog(RC_LOG_SERIOUS
1817 , "Signature check (on %s) failed (wrong key?); tried%s"
1818 , id_buf, s.tried);
1819 DBG(DBG_CONTROL,
1820 DBG_log("public key for %s failed:"
1821 " decrypted SIG payload into a malformed ECB (%s)"
1822 , id_buf, s.best_ugh + 1));
1823 }
1824 else
1825 {
1826 loglog(RC_LOG_SERIOUS
1827 , "Signature check (on %s) failed:"
1828 " tried%s keys but none worked."
1829 , id_buf, s.tried);
1830 DBG(DBG_CONTROL,
1831 DBG_log("all %d public keys for %s failed:"
1832 " best decrypted SIG payload into a malformed ECB (%s)"
1833 , s.tried_cnt, id_buf, s.best_ugh + 1));
1834 }
1835 return STF_FAIL + INVALID_KEY_INFORMATION;
1836 }
1837 }
1838 }
1839
1840 static notification_t
1841 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
1842 {
1843 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
1844 size_t len = pbs_left(nonce_pbs);
1845
1846 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
1847 {
1848 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
1849 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
1850 return PAYLOAD_MALFORMED; /* ??? */
1851 }
1852 clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
1853 return NOTHING_WRONG;
1854 }
1855
1856 /* encrypt message, sans fixed part of header
1857 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1858 * The theory is that there will be no "backing out", so we commit to IV.
1859 * We also close the pbs.
1860 */
1861 bool
1862 encrypt_message(pb_stream *pbs, struct state *st)
1863 {
1864 const struct encrypt_desc *e = st->st_oakley.encrypter;
1865 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
1866 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
1867
1868 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
1869
1870 /* Pad up to multiple of encryption blocksize.
1871 * See the description associated with the definition of
1872 * struct isakmp_hdr in packet.h.
1873 */
1874 {
1875 size_t padding = pad_up(enc_len, e->enc_blocksize);
1876
1877 if (padding != 0)
1878 {
1879 if (!out_zero(padding, pbs, "encryption padding"))
1880 return FALSE;
1881 enc_len += padding;
1882 }
1883 }
1884
1885 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1886
1887 /* e->crypt(TRUE, enc_start, enc_len, st); */
1888 crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
1889
1890 update_iv(st);
1891 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
1892 close_message(pbs);
1893 return TRUE;
1894 }
1895
1896 /* Compute HASH(1), HASH(2) of Quick Mode.
1897 * HASH(1) is part of Quick I1 message.
1898 * HASH(2) is part of Quick R1 message.
1899 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1900 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1901 */
1902 static size_t
1903 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
1904 , const struct state *st, const msgid_t *msgid, bool hash2)
1905 {
1906 struct hmac_ctx ctx;
1907
1908 #if 0 /* if desperate to debug hashing */
1909 # define hmac_update(ctx, ptr, len) { \
1910 DBG_dump("hash input", (ptr), (len)); \
1911 (hmac_update)((ctx), (ptr), (len)); \
1912 }
1913 DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
1914 #endif
1915 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1916 hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
1917 if (hash2)
1918 hmac_update_chunk(&ctx, st->st_ni); /* include Ni_b in the hash */
1919 hmac_update(&ctx, start, roof-start);
1920 hmac_final(dest, &ctx);
1921
1922 DBG(DBG_CRYPT,
1923 DBG_log("HASH(%d) computed:", hash2 + 1);
1924 DBG_dump("", dest, ctx.hmac_digest_size));
1925 return ctx.hmac_digest_size;
1926 # undef hmac_update
1927 }
1928
1929 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1930 * Used by: quick_inR1_outI2, quick_inI2
1931 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1932 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1933 * Message ID and Nonces. This is a mistake.
1934 */
1935 static size_t
1936 quick_mode_hash3(u_char *dest, struct state *st)
1937 {
1938 struct hmac_ctx ctx;
1939
1940 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1941 hmac_update(&ctx, "\0", 1);
1942 hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
1943 hmac_update_chunk(&ctx, st->st_ni);
1944 hmac_update_chunk(&ctx, st->st_nr);
1945 hmac_final(dest, &ctx);
1946 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
1947 return ctx.hmac_digest_size;
1948 }
1949
1950 /* Compute Phase 2 IV.
1951 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1952 */
1953 void
1954 init_phase2_iv(struct state *st, const msgid_t *msgid)
1955 {
1956 const struct hash_desc *h = st->st_oakley.hasher;
1957 union hash_ctx ctx;
1958
1959 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
1960 , st->st_ph1_iv, st->st_ph1_iv_len);
1961
1962 st->st_new_iv_len = h->hash_digest_size;
1963 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1964
1965 h->hash_init(&ctx);
1966 h->hash_update(&ctx, st->st_ph1_iv, st->st_ph1_iv_len);
1967 passert(*msgid != 0);
1968 h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
1969 h->hash_final(st->st_new_iv, &ctx);
1970
1971 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
1972 , st->st_new_iv, st->st_new_iv_len);
1973 }
1974
1975 /* Initiate quick mode.
1976 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1977 * (see RFC 2409 "IKE" 5.5)
1978 * Note: this is not called from demux.c
1979 */
1980
1981 static bool
1982 emit_subnet_id(ip_subnet *net
1983 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
1984 {
1985 struct isakmp_ipsec_id id;
1986 pb_stream id_pbs;
1987 ip_address ta;
1988 const unsigned char *tbp;
1989 size_t tal;
1990
1991 id.isaiid_np = np;
1992 id.isaiid_idtype = subnetishost(net)
1993 ? aftoinfo(subnettypeof(net))->id_addr
1994 : aftoinfo(subnettypeof(net))->id_subnet;
1995 id.isaiid_protoid = protoid;
1996 id.isaiid_port = port;
1997
1998 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
1999 return FALSE;
2000
2001 networkof(net, &ta);
2002 tal = addrbytesptr(&ta, &tbp);
2003 if (!out_raw(tbp, tal, &id_pbs, "client network"))
2004 return FALSE;
2005
2006 if (!subnetishost(net))
2007 {
2008 maskof(net, &ta);
2009 tal = addrbytesptr(&ta, &tbp);
2010 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2011 return FALSE;
2012 }
2013
2014 close_output_pbs(&id_pbs);
2015 return TRUE;
2016 }
2017
2018 stf_status
2019 quick_outI1(int whack_sock
2020 , struct state *isakmp_sa
2021 , struct connection *c
2022 , lset_t policy
2023 , unsigned long try
2024 , so_serial_t replacing)
2025 {
2026 struct state *st = duplicate_state(isakmp_sa);
2027 pb_stream reply; /* not really a reply */
2028 pb_stream rbody;
2029 u_char /* set by START_HASH_PAYLOAD: */
2030 *r_hashval, /* where in reply to jam hash value */
2031 *r_hash_start; /* start of what is to be hashed */
2032 bool has_client = c->spd.this.has_client || c->spd.that.has_client ||
2033 c->spd.this.protocol || c->spd.that.protocol ||
2034 c->spd.this.port || c->spd.that.port;
2035
2036 bool send_natoa = FALSE;
2037 u_int8_t np = ISAKMP_NEXT_NONE;
2038
2039 st->st_whack_sock = whack_sock;
2040 st->st_connection = c;
2041 set_cur_state(st); /* we must reset before exit */
2042 st->st_policy = policy;
2043 st->st_try = try;
2044
2045 st->st_myuserprotoid = c->spd.this.protocol;
2046 st->st_peeruserprotoid = c->spd.that.protocol;
2047 st->st_myuserport = c->spd.this.port;
2048 st->st_peeruserport = c->spd.that.port;
2049
2050 st->st_msgid = generate_msgid(isakmp_sa);
2051 st->st_state = STATE_QUICK_I1;
2052
2053 insert_state(st); /* needs cookies, connection, and msgid */
2054
2055 if (replacing == SOS_NOBODY)
2056 plog("initiating Quick Mode %s {using isakmp#%lu}"
2057 , prettypolicy(policy)
2058 , isakmp_sa->st_serialno);
2059 else
2060 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2061 , prettypolicy(policy)
2062 , replacing
2063 , isakmp_sa->st_serialno);
2064
2065 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
2066 {
2067 /* Duplicate nat_traversal status in new state */
2068 st->nat_traversal = isakmp_sa->nat_traversal;
2069
2070 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
2071 has_client = TRUE;
2072
2073 nat_traversal_change_port_lookup(NULL, st);
2074 }
2075 else
2076 st->nat_traversal = 0;
2077
2078 /* are we going to send a NAT-OA payload? */
2079 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2080 && !(st->st_policy & POLICY_TUNNEL)
2081 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2082 {
2083 send_natoa = TRUE;
2084 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2085 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2086 }
2087
2088 /* set up reply */
2089 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2090
2091 /* HDR* out */
2092 {
2093 struct isakmp_hdr hdr;
2094
2095 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2096 hdr.isa_np = ISAKMP_NEXT_HASH;
2097 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2098 hdr.isa_msgid = st->st_msgid;
2099 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2100 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2101 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2102 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2103 {
2104 reset_cur_state();
2105 return STF_INTERNAL_ERROR;
2106 }
2107 }
2108
2109 /* HASH(1) -- create and note space to be filled later */
2110 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2111
2112 /* SA out */
2113
2114 /*
2115 * See if pfs_group has been specified for this conn,
2116 * if not, fallback to old use-same-as-P1 behaviour
2117 */
2118 #ifndef NO_IKE_ALG
2119 if (st->st_connection)
2120 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2121 if (!st->st_pfs_group)
2122 #endif
2123 /* If PFS specified, use the same group as during Phase 1:
2124 * since no negotiation is possible, we pick one that is
2125 * very likely supported.
2126 */
2127 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2128
2129 /* Emit SA payload based on a subset of the policy bits.
2130 * POLICY_COMPRESS is considered iff we can do IPcomp.
2131 */
2132 {
2133 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2134
2135 if (can_do_IPcomp)
2136 pm |= POLICY_COMPRESS;
2137
2138 if (!out_sa(&rbody
2139 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2140 , st, FALSE, ISAKMP_NEXT_NONCE))
2141 {
2142 reset_cur_state();
2143 return STF_INTERNAL_ERROR;
2144 }
2145 }
2146
2147 /* Ni out */
2148 if (!build_and_ship_nonce(&st->st_ni, &rbody
2149 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2150 , "Ni"))
2151 {
2152 reset_cur_state();
2153 return STF_INTERNAL_ERROR;
2154 }
2155
2156 /* [ KE ] out (for PFS) */
2157
2158 if (st->st_pfs_group != NULL)
2159 {
2160 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2161 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2162 {
2163 reset_cur_state();
2164 return STF_INTERNAL_ERROR;
2165 }
2166 }
2167
2168 /* [ IDci, IDcr ] out */
2169 if (has_client)
2170 {
2171 /* IDci (we are initiator), then IDcr (peer is responder) */
2172 if (!emit_subnet_id(&c->spd.this.client
2173 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2174 || !emit_subnet_id(&c->spd.that.client
2175 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2176 {
2177 reset_cur_state();
2178 return STF_INTERNAL_ERROR;
2179 }
2180 }
2181
2182 /* Send NAT-OA if our address is NATed */
2183 if (send_natoa)
2184 {
2185 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2186 {
2187 reset_cur_state();
2188 return STF_INTERNAL_ERROR;
2189 }
2190 }
2191
2192 /* finish computing HASH(1), inserting it in output */
2193 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2194 , st, &st->st_msgid, FALSE);
2195
2196 /* encrypt message, except for fixed part of header */
2197
2198 init_phase2_iv(isakmp_sa, &st->st_msgid);
2199 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2200 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2201
2202 if (!encrypt_message(&rbody, st))
2203 {
2204 reset_cur_state();
2205 return STF_INTERNAL_ERROR;
2206 }
2207
2208 /* save packet, now that we know its size */
2209 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2210 , "reply packet from quick_outI1");
2211
2212 /* send the packet */
2213
2214 send_packet(st, "quick_outI1");
2215
2216 delete_event(st);
2217 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2218
2219 if (replacing == SOS_NOBODY)
2220 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2221 , "%s: initiate"
2222 , enum_name(&state_names, st->st_state));
2223 else
2224 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2225 , "%s: initiate to replace #%lu"
2226 , enum_name(&state_names, st->st_state)
2227 , replacing);
2228 reset_cur_state();
2229 return STF_OK;
2230 }
2231
2232
2233 /*
2234 * Decode the CERT payload of Phase 1.
2235 */
2236 static void
2237 decode_cert(struct msg_digest *md)
2238 {
2239 struct payload_digest *p;
2240
2241 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2242 {
2243 struct isakmp_cert *const cert = &p->payload.cert;
2244 chunk_t blob;
2245 time_t valid_until;
2246 blob.ptr = p->pbs.cur;
2247 blob.len = pbs_left(&p->pbs);
2248 if (cert->isacert_type == CERT_X509_SIGNATURE)
2249 {
2250 x509cert_t cert = empty_x509cert;
2251 if (parse_x509cert(blob, 0, &cert))
2252 {
2253 if (verify_x509cert(&cert, strict_crl_policy, &valid_until))
2254 {
2255 DBG(DBG_PARSING,
2256 DBG_log("Public key validated")
2257 )
2258 add_x509_public_key(&cert, valid_until, DAL_SIGNED);
2259 }
2260 else
2261 {
2262 plog("X.509 certificate rejected");
2263 }
2264 free_generalNames(cert.subjectAltName, FALSE);
2265 free_generalNames(cert.crlDistributionPoints, FALSE);
2266 }
2267 else
2268 plog("Syntax error in X.509 certificate");
2269 }
2270 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2271 {
2272 x509cert_t *cert = NULL;
2273
2274 if (pkcs7_parse_signedData(blob, NULL, &cert, NULL, NULL))
2275 store_x509certs(&cert, strict_crl_policy);
2276 else
2277 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2278 }
2279 else
2280 {
2281 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2282 enum_show(&cert_type_names, cert->isacert_type));
2283 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2284 }
2285 }
2286 }
2287
2288 /*
2289 * Decode the CR payload of Phase 1.
2290 */
2291 static void
2292 decode_cr(struct msg_digest *md, struct connection *c)
2293 {
2294 struct payload_digest *p;
2295
2296 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2297 {
2298 struct isakmp_cr *const cr = &p->payload.cr;
2299 chunk_t ca_name;
2300
2301 ca_name.len = pbs_left(&p->pbs);
2302 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2303
2304 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2305
2306 if (cr->isacr_type == CERT_X509_SIGNATURE)
2307 {
2308 char buf[BUF_LEN];
2309
2310 if (ca_name.len > 0)
2311 {
2312 generalName_t *gn;
2313
2314 if (!is_asn1(ca_name))
2315 continue;
2316
2317 gn = alloc_thing(generalName_t, "generalName");
2318 clonetochunk(ca_name, ca_name.ptr,ca_name.len, "ca name");
2319 gn->kind = GN_DIRECTORY_NAME;
2320 gn->name = ca_name;
2321 gn->next = c->requested_ca;
2322 c->requested_ca = gn;
2323 }
2324 c->got_certrequest = TRUE;
2325
2326 DBG(DBG_PARSING | DBG_CONTROL,
2327 dntoa_or_null(buf, BUF_LEN, ca_name, "%any");
2328 DBG_log("requested CA: '%s'", buf);
2329 )
2330 }
2331 else
2332 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2333 enum_show(&cert_type_names, cr->isacr_type));
2334 }
2335 }
2336
2337 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2338 * Note: we may change connections as a result.
2339 * We must be called before SIG or HASH are decoded since we
2340 * may change the peer's RSA key or ID.
2341 */
2342 static bool
2343 decode_peer_id(struct msg_digest *md, struct id *peer)
2344 {
2345 struct state *const st = md->st;
2346 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2347 const pb_stream *const id_pbs = &id_pld->pbs;
2348 struct isakmp_id *const id = &id_pld->payload.id;
2349
2350 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2351 * It talks about the protocol ID and Port fields of the ID
2352 * Payload, but they don't exist as such in Phase 1.
2353 * We use more appropriate names.
2354 * isaid_doi_specific_a is in place of Protocol ID.
2355 * isaid_doi_specific_b is in place of Port.
2356 * Besides, there is no good reason for allowing these to be
2357 * other than 0 in Phase 1.
2358 */
2359 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2360 && id->isaid_doi_specific_a == IPPROTO_UDP
2361 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2362 {
2363 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2364 "accepted with port_floating NAT-T",
2365 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2366 }
2367 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2368 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2369 {
2370 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2371 " but are %d/%d"
2372 , IPPROTO_UDP, IKE_UDP_PORT
2373 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2374 return FALSE;
2375 }
2376
2377 peer->kind = id->isaid_idtype;
2378
2379 switch (peer->kind)
2380 {
2381 case ID_IPV4_ADDR:
2382 case ID_IPV6_ADDR:
2383 /* failure mode for initaddr is probably inappropriate address length */
2384 {
2385 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2386 , peer->kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2387 , &peer->ip_addr);
2388
2389 if (ugh != NULL)
2390 {
2391 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2392 , enum_show(&ident_names, peer->kind), ugh);
2393 /* XXX Could send notification back */
2394 return FALSE;
2395 }
2396 }
2397 break;
2398
2399 case ID_USER_FQDN:
2400 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2401 {
2402 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2403 return FALSE;
2404 }
2405 /* FALLTHROUGH */
2406 case ID_FQDN:
2407 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2408 {
2409 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2410 , enum_show(&ident_names, peer->kind));
2411 return FALSE;
2412 }
2413
2414 /* ??? ought to do some more sanity check, but what? */
2415
2416 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2417 break;
2418
2419 case ID_KEY_ID:
2420 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2421 DBG(DBG_PARSING,
2422 DBG_dump_chunk("KEY ID:", peer->name));
2423 break;
2424
2425 case ID_DER_ASN1_DN:
2426 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2427 DBG(DBG_PARSING,
2428 DBG_dump_chunk("DER ASN1 DN:", peer->name));
2429 break;
2430
2431 default:
2432 /* XXX Could send notification back */
2433 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2434 , enum_show(&ident_names, peer->kind));
2435 return FALSE;
2436 }
2437
2438 {
2439 char buf[BUF_LEN];
2440
2441 idtoa(peer, buf, sizeof(buf));
2442 plog("Peer ID is %s: '%s'",
2443 enum_show(&ident_names, id->isaid_idtype), buf);
2444 }
2445
2446 /* check for certificates */
2447 decode_cert(md);
2448 return TRUE;
2449 }
2450
2451 /* Now that we've decoded the ID payload, let's see if we
2452 * need to switch connections.
2453 * We must not switch horses if we initiated:
2454 * - if the initiation was explicit, we'd be ignoring user's intent
2455 * - if opportunistic, we'll lose our HOLD info
2456 */
2457 static bool
2458 switch_connection(struct msg_digest *md, struct id *peer, bool initiator)
2459 {
2460 struct state *const st = md->st;
2461 struct connection *c = st->st_connection;
2462
2463 chunk_t peer_ca = (st->st_peer_pubkey != NULL)
2464 ? st->st_peer_pubkey->issuer : empty_chunk;
2465
2466 DBG(DBG_CONTROL,
2467 char buf[BUF_LEN];
2468
2469 dntoa_or_null(buf, BUF_LEN, peer_ca, "%none");
2470 DBG_log("peer CA: '%s'", buf);
2471 )
2472
2473 if (initiator)
2474 {
2475 int pathlen;
2476
2477 if (!same_id(&c->spd.that.id, peer))
2478 {
2479 char expect[BUF_LEN]
2480 , found[BUF_LEN];
2481
2482 idtoa(&c->spd.that.id, expect, sizeof(expect));
2483 idtoa(peer, found, sizeof(found));
2484 loglog(RC_LOG_SERIOUS
2485 , "we require peer to have ID '%s', but peer declares '%s'"
2486 , expect, found);
2487 return FALSE;
2488 }
2489
2490 DBG(DBG_CONTROL,
2491 char buf[BUF_LEN];
2492
2493 dntoa_or_null(buf, BUF_LEN, c->spd.that.ca, "%none");
2494 DBG_log("required CA: '%s'", buf);
2495 )
2496
2497 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2498 {
2499 loglog(RC_LOG_SERIOUS
2500 , "we don't accept the peer's CA");
2501 return FALSE;
2502 }
2503 }
2504 else
2505 {
2506 struct connection *r;
2507
2508 /* check for certificate requests */
2509 decode_cr(md, c);
2510
2511 r = refine_host_connection(st, peer, peer_ca);
2512
2513 /* delete the collected certificate requests */
2514 free_generalNames(c->requested_ca, TRUE);
2515 c->requested_ca = NULL;
2516
2517 if (r == NULL)
2518 {
2519 char buf[BUF_LEN];
2520
2521 idtoa(peer, buf, sizeof(buf));
2522 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2523 return FALSE;
2524 }
2525
2526 DBG(DBG_CONTROL,
2527 char buf[BUF_LEN];
2528
2529 dntoa_or_null(buf, BUF_LEN, r->spd.this.ca, "%none");
2530 DBG_log("offered CA: '%s'", buf);
2531 )
2532
2533 if (r != c)
2534 {
2535 /* apparently, r is an improvement on c -- replace */
2536
2537 DBG(DBG_CONTROL
2538 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2539 if (r->kind == CK_TEMPLATE)
2540 {
2541 /* instantiate it, filling in peer's ID */
2542 r = rw_instantiate(r, &c->spd.that.host_addr
2543 , c->spd.that.host_port, NULL, peer);
2544 }
2545
2546 /* copy certificate request info */
2547 r->got_certrequest = c->got_certrequest;
2548
2549 st->st_connection = r; /* kill reference to c */
2550 set_cur_connection(r);
2551 connection_discard(c);
2552 }
2553 else if (c->spd.that.has_id_wildcards)
2554 {
2555 free_id_content(&c->spd.that.id);
2556 c->spd.that.id = *peer;
2557 c->spd.that.has_id_wildcards = FALSE;
2558 unshare_id_content(&c->spd.that.id);
2559 }
2560 }
2561 return TRUE;
2562 }
2563
2564 /* Decode the variable part of an ID packet (during Quick Mode).
2565 * This is designed for packets that identify clients, not peers.
2566 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2567 * (1) it is wrong and (2) we use this value for inband signalling.
2568 */
2569 static bool
2570 decode_net_id(struct isakmp_ipsec_id *id
2571 , pb_stream *id_pbs
2572 , ip_subnet *net
2573 , const char *which)
2574 {
2575 const struct af_info *afi = NULL;
2576
2577 /* Note: the following may be a pointer into static memory
2578 * that may be recycled, but only if the type is not known.
2579 * That case is disposed of very early -- in the first switch.
2580 */
2581 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2582
2583 switch (id->isaiid_idtype)
2584 {
2585 case ID_IPV4_ADDR:
2586 case ID_IPV4_ADDR_SUBNET:
2587 case ID_IPV4_ADDR_RANGE:
2588 afi = &af_inet4_info;
2589 break;
2590 case ID_IPV6_ADDR:
2591 case ID_IPV6_ADDR_SUBNET:
2592 case ID_IPV6_ADDR_RANGE:
2593 afi = &af_inet6_info;
2594 break;
2595 case ID_FQDN:
2596 return TRUE;
2597 default:
2598 /* XXX support more */
2599 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2600 , idtypename);
2601 /* XXX Could send notification back */
2602 return FALSE;
2603 }
2604
2605 switch (id->isaiid_idtype)
2606 {
2607 case ID_IPV4_ADDR:
2608 case ID_IPV6_ADDR:
2609 {
2610 ip_address temp_address;
2611 err_t ugh;
2612
2613 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2614
2615 if (ugh != NULL)
2616 {
2617 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2618 , which, idtypename, ugh);
2619 /* XXX Could send notification back */
2620 return FALSE;
2621 }
2622 if (isanyaddr(&temp_address))
2623 {
2624 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2625 , which, idtypename, ip_str(&temp_address));
2626 /* XXX Could send notification back */
2627 return FALSE;
2628 }
2629 happy(addrtosubnet(&temp_address, net));
2630 DBG(DBG_PARSING | DBG_CONTROL
2631 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2632 break;
2633 }
2634
2635 case ID_IPV4_ADDR_SUBNET:
2636 case ID_IPV6_ADDR_SUBNET:
2637 {
2638 ip_address temp_address, temp_mask;
2639 err_t ugh;
2640
2641 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2642 {
2643 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2644 , which, idtypename);
2645 /* XXX Could send notification back */
2646 return FALSE;
2647 }
2648 ugh = initaddr(id_pbs->cur
2649 , afi->ia_sz, afi->af, &temp_address);
2650 if (ugh == NULL)
2651 ugh = initaddr(id_pbs->cur + afi->ia_sz
2652 , afi->ia_sz, afi->af, &temp_mask);
2653 if (ugh == NULL)
2654 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2655 , '0', net);
2656 if (ugh == NULL && subnetisnone(net))
2657 ugh = "contains only anyaddr";
2658 if (ugh != NULL)
2659 {
2660 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2661 , which, idtypename, ugh);
2662 /* XXX Could send notification back */
2663 return FALSE;
2664 }
2665 DBG(DBG_PARSING | DBG_CONTROL,
2666 {
2667 char temp_buff[SUBNETTOT_BUF];
2668
2669 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2670 DBG_log("%s is subnet %s", which, temp_buff);
2671 });
2672 break;
2673 }
2674
2675 case ID_IPV4_ADDR_RANGE:
2676 case ID_IPV6_ADDR_RANGE:
2677 {
2678 ip_address temp_address_from, temp_address_to;
2679 err_t ugh;
2680
2681 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2682 {
2683 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2684 , which, idtypename);
2685 /* XXX Could send notification back */
2686 return FALSE;
2687 }
2688 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2689 if (ugh == NULL)
2690 ugh = initaddr(id_pbs->cur + afi->ia_sz
2691 , afi->ia_sz, afi->af, &temp_address_to);
2692 if (ugh != NULL)
2693 {
2694 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2695 , which, idtypename, ugh);
2696 /* XXX Could send notification back */
2697 return FALSE;
2698 }
2699
2700 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2701 if (ugh == NULL && subnetisnone(net))
2702 ugh = "contains only anyaddr";
2703 if (ugh != NULL)
2704 {
2705 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2706
2707 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2708 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2709 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2710 " %s - %s unacceptable: %s"
2711 , which, idtypename, temp_buff1, temp_buff2, ugh);
2712 return FALSE;
2713 }
2714 DBG(DBG_PARSING | DBG_CONTROL,
2715 {
2716 char temp_buff[SUBNETTOT_BUF];
2717
2718 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2719 DBG_log("%s is subnet %s (received as range)"
2720 , which, temp_buff);
2721 });
2722 break;
2723 }
2724 }
2725
2726 /* set the port selector */
2727 setportof(htons(id->isaiid_port), &net->addr);
2728
2729 DBG(DBG_PARSING | DBG_CONTROL,
2730 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2731 )
2732
2733 return TRUE;
2734 }
2735
2736 /* like decode, but checks that what is received matches what was sent */
2737 static bool
2738
2739 check_net_id(struct isakmp_ipsec_id *id
2740 , pb_stream *id_pbs
2741 , u_int8_t *protoid
2742 , u_int16_t *port
2743 , ip_subnet *net
2744 , const char *which)
2745 {
2746 ip_subnet net_temp;
2747
2748 if (!decode_net_id(id, id_pbs, &net_temp, which))
2749 return FALSE;
2750
2751 if (!samesubnet(net, &net_temp)
2752 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2753 {
2754 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2755 return FALSE;
2756 }
2757 return TRUE;
2758 }
2759
2760 /*
2761 * look for the existence of a non-expiring preloaded public key
2762 */
2763 static bool
2764 has_preloaded_public_key(struct state *st)
2765 {
2766 struct connection *c = st->st_connection;
2767
2768 /* do not consider rw connections since
2769 * the peer's identity must be known
2770 */
2771 if (c->kind == CK_PERMANENT)
2772 {
2773 pubkey_list_t *p;
2774
2775 /* look for a matching RSA public key */
2776 for (p = pubkeys; p != NULL; p = p->next)
2777 {
2778 pubkey_t *key = p->key;
2779
2780 if (key->alg == PUBKEY_ALG_RSA &&
2781 same_id(&c->spd.that.id, &key->id) &&
2782 key->until_time == UNDEFINED_TIME)
2783 {
2784 /* found a preloaded public key */
2785 return TRUE;
2786 }
2787 }
2788 }
2789 return FALSE;
2790 }
2791
2792 /*
2793 * Produce the new key material of Quick Mode.
2794 * RFC 2409 "IKE" section 5.5
2795 * specifies how this is to be done.
2796 */
2797 static void
2798 compute_proto_keymat(struct state *st
2799 , u_int8_t protoid
2800 , struct ipsec_proto_info *pi)
2801 {
2802 size_t needed_len = 0; /* bytes of keying material needed */
2803
2804 /* Add up the requirements for keying material
2805 * (It probably doesn't matter if we produce too much!)
2806 */
2807 switch (protoid)
2808 {
2809 case PROTO_IPSEC_ESP:
2810 switch (pi->attrs.transid)
2811 {
2812 case ESP_NULL:
2813 needed_len = 0;
2814 break;
2815 case ESP_DES:
2816 needed_len = DES_CBC_BLOCK_SIZE;
2817 break;
2818 case ESP_3DES:
2819 needed_len = DES_CBC_BLOCK_SIZE * 3;
2820 break;
2821 default:
2822 #ifndef NO_KERNEL_ALG
2823 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2824 /* XXX: check key_len "coupling with kernel.c's */
2825 if (pi->attrs.key_len) {
2826 needed_len=pi->attrs.key_len/8;
2827 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2828 "key_len=%d from peer",
2829 (int)needed_len));
2830 }
2831 break;
2832 }
2833 #endif
2834 bad_case(pi->attrs.transid);
2835 }
2836
2837 #ifndef NO_KERNEL_ALG
2838 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2839 "needed_len (after ESP enc)=%d",
2840 (int)needed_len));
2841 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2842 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2843 } else
2844 #endif
2845 switch (pi->attrs.auth)
2846 {
2847 case AUTH_ALGORITHM_NONE:
2848 break;
2849 case AUTH_ALGORITHM_HMAC_MD5:
2850 needed_len += HMAC_MD5_KEY_LEN;
2851 break;
2852 case AUTH_ALGORITHM_HMAC_SHA1:
2853 needed_len += HMAC_SHA1_KEY_LEN;
2854 break;
2855 case AUTH_ALGORITHM_DES_MAC:
2856 default:
2857 bad_case(pi->attrs.auth);
2858 }
2859 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2860 "needed_len (after ESP auth)=%d",
2861 (int)needed_len));
2862 break;
2863
2864 case PROTO_IPSEC_AH:
2865 switch (pi->attrs.transid)
2866 {
2867 case AH_MD5:
2868 needed_len = HMAC_MD5_KEY_LEN;
2869 break;
2870 case AH_SHA:
2871 needed_len = HMAC_SHA1_KEY_LEN;
2872 break;
2873 default:
2874 bad_case(pi->attrs.transid);
2875 }
2876 break;
2877
2878 default:
2879 bad_case(protoid);
2880 }
2881
2882 pi->keymat_len = needed_len;
2883
2884 /* Allocate space for the keying material.
2885 * Although only needed_len bytes are desired, we
2886 * must round up to a multiple of ctx.hmac_digest_size
2887 * so that our buffer isn't overrun.
2888 */
2889 {
2890 struct hmac_ctx ctx_me, ctx_peer;
2891 size_t needed_space; /* space needed for keying material (rounded up) */
2892 size_t i;
2893
2894 hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
2895 ctx_peer = ctx_me; /* duplicate initial conditions */
2896
2897 needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
2898 replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
2899 replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
2900
2901 for (i = 0;; )
2902 {
2903 if (st->st_shared.ptr != NULL)
2904 {
2905 /* PFS: include the g^xy */
2906 hmac_update_chunk(&ctx_me, st->st_shared);
2907 hmac_update_chunk(&ctx_peer, st->st_shared);
2908 }
2909 hmac_update(&ctx_me, &protoid, sizeof(protoid));
2910 hmac_update(&ctx_peer, &protoid, sizeof(protoid));
2911
2912 hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
2913 hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
2914
2915 hmac_update_chunk(&ctx_me, st->st_ni);
2916 hmac_update_chunk(&ctx_peer, st->st_ni);
2917
2918 hmac_update_chunk(&ctx_me, st->st_nr);
2919 hmac_update_chunk(&ctx_peer, st->st_nr);
2920
2921 hmac_final(pi->our_keymat + i, &ctx_me);
2922 hmac_final(pi->peer_keymat + i, &ctx_peer);
2923
2924 i += ctx_me.hmac_digest_size;
2925 if (i >= needed_space)
2926 break;
2927
2928 /* more keying material needed: prepare to go around again */
2929
2930 hmac_reinit(&ctx_me);
2931 hmac_reinit(&ctx_peer);
2932
2933 hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size
2934 , ctx_me.hmac_digest_size);
2935 hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size
2936 , ctx_peer.hmac_digest_size);
2937 }
2938 }
2939
2940 DBG(DBG_CRYPT,
2941 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2942 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2943 }
2944
2945 static void
2946 compute_keymats(struct state *st)
2947 {
2948 if (st->st_ah.present)
2949 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2950 if (st->st_esp.present)
2951 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2952 }
2953
2954 /* State Transition Functions.
2955 *
2956 * The definition of state_microcode_table in demux.c is a good
2957 * overview of these routines.
2958 *
2959 * - Called from process_packet; result handled by complete_state_transition
2960 * - struct state_microcode member "processor" points to these
2961 * - these routine definitionss are in state order
2962 * - these routines must be restartable from any point of error return:
2963 * beware of memory allocated before any error.
2964 * - output HDR is usually emitted by process_packet (if state_microcode
2965 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2966 *
2967 * The transition functions' functions include:
2968 * - process and judge payloads
2969 * - update st_iv (result of decryption is in st_new_iv)
2970 * - build reply packet
2971 */
2972
2973 /* Handle a Main Mode Oakley first packet (responder side).
2974 * HDR;SA --> HDR;SA
2975 */
2976 stf_status
2977 main_inI1_outR1(struct msg_digest *md)
2978 {
2979 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2980 struct state *st;
2981 struct connection *c;
2982 struct isakmp_proposal proposal;
2983 pb_stream proposal_pbs;
2984 pb_stream r_sa_pbs;
2985 u_int32_t ipsecdoisit;
2986 lset_t policy = LEMPTY;
2987 int vids_to_send = 0;
2988
2989 /* We preparse the peer's proposal in order to determine
2990 * the requested authentication policy (RSA or PSK)
2991 */
2992 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2993 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2994
2995 backup_pbs(&proposal_pbs);
2996 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2997 , proposal.isap_notrans, &policy));
2998 restore_pbs(&proposal_pbs);
2999
3000 /* We are only considering candidate connections that match
3001 * the requested authentication policy (RSA or PSK)
3002 */
3003 c = find_host_connection(&md->iface->addr, pluto_port
3004 , &md->sender, md->sender_port, policy);
3005
3006 if (c == NULL && md->iface->ike_float)
3007 {
3008 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
3009 , &md->sender, md->sender_port, policy);
3010 }
3011
3012 if (c == NULL)
3013 {
3014 /* See if a wildcarded connection can be found.
3015 * We cannot pick the right connection, so we're making a guess.
3016 * All Road Warrior connections are fair game:
3017 * we pick the first we come across (if any).
3018 * If we don't find any, we pick the first opportunistic
3019 * with the smallest subnet that includes the peer.
3020 * There is, of course, no necessary relationship between
3021 * an Initiator's address and that of its client,
3022 * but Food Groups kind of assumes one.
3023 */
3024 {
3025 struct connection *d;
3026
3027 d = find_host_connection(&md->iface->addr
3028 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3029
3030 for (; d != NULL; d = d->hp_next)
3031 {
3032 if (d->kind == CK_GROUP)
3033 {
3034 /* ignore */
3035 }
3036 else
3037 {
3038 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3039 {
3040 /* must be Road Warrior: we have a winner */
3041 c = d;
3042 break;
3043 }
3044
3045 /* Opportunistic or Shunt: pick tightest match */
3046 if (addrinsubnet(&md->sender, &d->spd.that.client)
3047 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3048 c = d;
3049 }
3050 }
3051 }
3052
3053 if (c == NULL)
3054 {
3055 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3056 " but no connection has been authorized%s%s"
3057 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3058 , (policy != LEMPTY) ? " with policy=" : ""
3059 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3060 /* XXX notification is in order! */
3061 return STF_IGNORE;
3062 }
3063 else if (c->kind != CK_TEMPLATE)
3064 {
3065 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3066 " but \"%s\" forbids connection"
3067 , ip_str(&md->iface->addr), pluto_port, c->name);
3068 /* XXX notification is in order! */
3069 return STF_IGNORE;
3070 }
3071 else
3072 {
3073 /* Create a temporary connection that is a copy of this one.
3074 * His ID isn't declared yet.
3075 */
3076 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3077 }
3078 }
3079 else if (c->kind == CK_TEMPLATE)
3080 {
3081 /* Create an instance
3082 * This is a rare case: wildcard peer ID but static peer IP address
3083 */
3084 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, &c->spd.that.id);
3085 }
3086
3087 /* Set up state */
3088 md->st = st = new_state();
3089 st->st_connection = c;
3090 set_cur_state(st); /* (caller will reset cur_state) */
3091 st->st_try = 0; /* not our job to try again from start */
3092 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3093
3094 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3095 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3096
3097 insert_state(st); /* needs cookies, connection, and msgid (0) */
3098
3099 st->st_doi = ISAKMP_DOI_IPSEC;
3100 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3101
3102 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3103 {
3104 plog("responding to Main Mode from unknown peer %s:%u"
3105 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3106 }
3107 else if (c->kind == CK_INSTANCE)
3108 {
3109 plog("responding to Main Mode from unknown peer %s"
3110 , ip_str(&c->spd.that.host_addr));
3111 }
3112 else
3113 {
3114 plog("responding to Main Mode");
3115 }
3116
3117 /* parse_isakmp_sa also spits out a winning SA into our reply,
3118 * so we have to build our md->reply and emit HDR before calling it.
3119 */
3120
3121 /* determine how many Vendor ID payloads we will be sending */
3122 if (SEND_PLUTO_VID)
3123 vids_to_send++;
3124 if (SEND_CISCO_UNITY_VID)
3125 vids_to_send++;
3126 if (md->openpgp)
3127 vids_to_send++;
3128 if (SEND_XAUTH_VID)
3129 vids_to_send++;
3130 /* always send DPD Vendor ID */
3131 vids_to_send++;
3132 if (md->nat_traversal_vid && nat_traversal_enabled)
3133 vids_to_send++;
3134
3135 /* HDR out.
3136 * We can't leave this to comm_handle() because we must
3137 * fill in the cookie.
3138 */
3139 {
3140 struct isakmp_hdr r_hdr = md->hdr;
3141
3142 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3143 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3144 r_hdr.isa_np = ISAKMP_NEXT_SA;
3145 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3146 return STF_INTERNAL_ERROR;
3147 }
3148
3149 /* start of SA out */
3150 {
3151 struct isakmp_sa r_sa = sa_pd->payload.sa;
3152
3153 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3154
3155 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3156 return STF_INTERNAL_ERROR;
3157 }
3158
3159 /* SA body in and out */
3160 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3161 ,&proposal, &r_sa_pbs, st, FALSE));
3162
3163 /* if enabled send Pluto Vendor ID */
3164 if (SEND_PLUTO_VID)
3165 {
3166 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3167 , &md->rbody, VID_STRONGSWAN))
3168 {
3169 return STF_INTERNAL_ERROR;
3170 }
3171 }
3172
3173 /* if enabled send Cisco Unity Vendor ID */
3174 if (SEND_CISCO_UNITY_VID)
3175 {
3176 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3177 , &md->rbody, VID_CISCO_UNITY))
3178 {
3179 return STF_INTERNAL_ERROR;
3180 }
3181 }
3182
3183 /*
3184 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3185 */
3186 if (md->openpgp)
3187 {
3188 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3189 , &md->rbody, VID_OPENPGP))
3190 {
3191 return STF_INTERNAL_ERROR;
3192 }
3193 }
3194
3195 /* Announce our ability to do eXtended AUTHentication to the peer */
3196 if (SEND_XAUTH_VID)
3197 {
3198 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3199 , &md->rbody, VID_MISC_XAUTH))
3200 {
3201 return STF_INTERNAL_ERROR;
3202 }
3203 }
3204
3205 /* Announce our ability to do Dead Peer Detection to the peer */
3206 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3207 , &md->rbody, VID_MISC_DPD))
3208 {
3209 return STF_INTERNAL_ERROR;
3210 }
3211
3212 if (md->nat_traversal_vid && nat_traversal_enabled)
3213 {
3214 /* reply if NAT-Traversal draft is supported */
3215 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3216
3217 if (st->nat_traversal
3218 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3219 , &md->rbody, md->nat_traversal_vid))
3220 {
3221 return STF_INTERNAL_ERROR;
3222 }
3223 }
3224
3225 close_message(&md->rbody);
3226
3227 /* save initiator SA for HASH */
3228 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3229
3230 return STF_OK;
3231 }
3232
3233 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3234 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3235 *
3236 * The following are not yet implemented:
3237 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3238 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3239 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3240 *
3241 * We must verify that the proposal received matches one we sent.
3242 */
3243 stf_status
3244 main_inR1_outI2(struct msg_digest *md)
3245 {
3246 struct state *const st = md->st;
3247
3248 u_int8_t np = ISAKMP_NEXT_NONE;
3249
3250 /* verify echoed SA */
3251 {
3252 u_int32_t ipsecdoisit;
3253 pb_stream proposal_pbs;
3254 struct isakmp_proposal proposal;
3255 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3256
3257 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3258 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3259 if (proposal.isap_notrans != 1)
3260 {
3261 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3262 , (unsigned)proposal.isap_notrans);
3263 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX);
3264 }
3265 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3266 , &proposal_pbs, &proposal, NULL, st, TRUE));
3267 }
3268
3269 if (nat_traversal_enabled && md->nat_traversal_vid)
3270 {
3271 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3272 plog("enabling possible NAT-traversal with method %s"
3273 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3274 }
3275 if (st->nat_traversal & NAT_T_WITH_NATD)
3276 {
3277 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3278 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3279 }
3280
3281 /**************** build output packet HDR;KE;Ni ****************/
3282
3283 /* HDR out.
3284 * We can't leave this to comm_handle() because the isa_np
3285 * depends on the type of Auth (eventually).
3286 */
3287 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3288
3289 /* KE out */
3290 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3291 , &md->rbody, ISAKMP_NEXT_NONCE))
3292 return STF_INTERNAL_ERROR;
3293
3294 #ifdef DEBUG
3295 /* Ni out */
3296 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3297 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3298 return STF_INTERNAL_ERROR;
3299
3300 if (cur_debugging & IMPAIR_BUST_MI2)
3301 {
3302 /* generate a pointless large VID payload to push message over MTU */
3303 pb_stream vid_pbs;
3304
3305 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3306 return STF_INTERNAL_ERROR;
3307 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3308 return STF_INTERNAL_ERROR;
3309 close_output_pbs(&vid_pbs);
3310 }
3311 #else
3312 /* Ni out */
3313 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3314 return STF_INTERNAL_ERROR;
3315 #endif
3316
3317 if (st->nat_traversal & NAT_T_WITH_NATD)
3318 {
3319 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3320 return STF_INTERNAL_ERROR;
3321 }
3322
3323 /* finish message */
3324 close_message(&md->rbody);
3325
3326 /* Reinsert the state, using the responder cookie we just received */
3327 unhash_state(st);
3328 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3329 insert_state(st); /* needs cookies, connection, and msgid (0) */
3330
3331 return STF_OK;
3332 }
3333
3334 /* STATE_MAIN_R1:
3335 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3336 *
3337 * The following are not yet implemented:
3338 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3339 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3340 * RPKE_AUTH:
3341 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3342 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3343 */
3344 stf_status
3345 main_inI2_outR2(struct msg_digest *md)
3346 {
3347 struct state *const st = md->st;
3348 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3349
3350 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3351 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3352 || st->st_oakley.auth == XAUTHInitRSA
3353 || st->st_oakley.auth == XAUTHRespRSA;
3354 bool send_cr = !no_cr_send && RSA_auth && !has_preloaded_public_key(st);
3355
3356 u_int8_t np = ISAKMP_NEXT_NONE;
3357
3358 /* KE in */
3359 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3360
3361 /* Ni in */
3362 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3363
3364 if (st->nat_traversal & NAT_T_WITH_NATD)
3365 {
3366 nat_traversal_natd_lookup(md);
3367
3368 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3369 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3370 }
3371 if (st->nat_traversal)
3372 {
3373 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3374 }
3375 if (st->nat_traversal & NAT_T_WITH_KA)
3376 {
3377 nat_traversal_new_ka_event();
3378 }
3379
3380 /* decode certificate requests */
3381 st->st_connection->got_certrequest = FALSE;
3382 decode_cr(md, st->st_connection);
3383
3384 /**************** build output packet HDR;KE;Nr ****************/
3385
3386 /* HDR out done */
3387
3388 /* KE out */
3389 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3390 , &md->rbody, ISAKMP_NEXT_NONCE))
3391 return STF_INTERNAL_ERROR;
3392
3393 #ifdef DEBUG
3394 /* Nr out */
3395 if (!build_and_ship_nonce(&st->st_nr, &md->rbody
3396 , (cur_debugging & IMPAIR_BUST_MR2)? ISAKMP_NEXT_VID
3397 : (send_cr? ISAKMP_NEXT_CR : np), "Nr"))
3398 return STF_INTERNAL_ERROR;
3399
3400 if (cur_debugging & IMPAIR_BUST_MR2)
3401 {
3402 /* generate a pointless large VID payload to push message over MTU */
3403 pb_stream vid_pbs;
3404
3405 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : np,
3406 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3407 return STF_INTERNAL_ERROR;
3408 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3409 return STF_INTERNAL_ERROR;
3410 close_output_pbs(&vid_pbs);
3411 }
3412 #else
3413 /* Nr out */
3414 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3415 (send_cr)? ISAKMP_NEXT_CR : np, "Nr"))
3416 return STF_INTERNAL_ERROR;
3417 #endif
3418
3419 /* CR out */
3420 if (send_cr)
3421 {
3422 if (st->st_connection->kind == CK_PERMANENT)
3423 {
3424 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3425 , st->st_connection->spd.that.ca
3426 , &md->rbody, np))
3427 return STF_INTERNAL_ERROR;
3428 }
3429 else
3430 {
3431 generalName_t *ca = NULL;
3432
3433 if (collect_rw_ca_candidates(md, &ca))
3434 {
3435 generalName_t *gn;
3436
3437 for (gn = ca; gn != NULL; gn = gn->next)
3438 {
3439 if (!build_and_ship_CR(CERT_X509_SIGNATURE, gn->name
3440 , &md->rbody
3441 , gn->next == NULL ? np : ISAKMP_NEXT_CR))
3442 return STF_INTERNAL_ERROR;
3443 }
3444 free_generalNames(ca, FALSE);
3445 }
3446 else
3447 {
3448 if (!build_and_ship_CR(CERT_X509_SIGNATURE, empty_chunk
3449 , &md->rbody, np))
3450 return STF_INTERNAL_ERROR;
3451 }
3452 }
3453 }
3454
3455 if (st->nat_traversal & NAT_T_WITH_NATD)
3456 {
3457 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3458 return STF_INTERNAL_ERROR;
3459 }
3460
3461 /* finish message */
3462 close_message(&md->rbody);
3463
3464 /* next message will be encrypted, but not this one.
3465 * We could defer this calculation.
3466 */
3467 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3468 if (!generate_skeyids_iv(st))
3469 return STF_FAIL + AUTHENTICATION_FAILED;
3470 update_iv(st);
3471
3472 return STF_OK;
3473 }
3474
3475 /* STATE_MAIN_I2:
3476 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3477 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3478 *
3479 * The following are not yet implemented.
3480 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3481 * --> HDR*, HASH_I
3482 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3483 * --> HDR*, HASH_I
3484 */
3485 stf_status
3486 main_inR2_outI3(struct msg_digest *md)
3487 {
3488 struct state *const st = md->st;
3489 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3490 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3491
3492 certpolicy_t cert_policy = st->st_connection->spd.this.sendcert;
3493 cert_t mycert = st->st_connection->spd.this.cert;
3494 bool requested, send_cert, send_cr;
3495
3496 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3497 || st->st_oakley.auth == XAUTHInitRSA
3498 || st->st_oakley.auth == XAUTHRespRSA;
3499
3500 int auth_payload = RSA_auth ? ISAKMP_NEXT_SIG : ISAKMP_NEXT_HASH;
3501
3502 /* KE in */
3503 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3504
3505 /* Nr in */
3506 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3507
3508 /* decode certificate requests */
3509 st->st_connection->got_certrequest = FALSE;
3510 decode_cr(md, st->st_connection);
3511
3512 /* free collected certificate requests since as initiator
3513 * we don't heed them anyway
3514 */
3515 free_generalNames(st->st_connection->requested_ca, TRUE);
3516 st->st_connection->requested_ca = NULL;
3517
3518 /* send certificate if auth is RSA, we have one and we want
3519 * or are requested to send it
3520 */
3521 requested = cert_policy == CERT_SEND_IF_ASKED
3522 && st->st_connection->got_certrequest;
3523 send_cert = RSA_auth && mycert.type != CERT_NONE
3524 && (cert_policy == CERT_ALWAYS_SEND || requested);
3525
3526 /* send certificate request if we don't have a preloaded RSA public key */
3527 send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3528
3529 /* done parsing; initialize crypto */
3530 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3531 if (!generate_skeyids_iv(st))
3532 return STF_FAIL + AUTHENTICATION_FAILED;
3533
3534 if (st->nat_traversal & NAT_T_WITH_NATD)
3535 {
3536 nat_traversal_natd_lookup(md);
3537 }
3538 if (st->nat_traversal)
3539 {
3540 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3541 }
3542 if (st->nat_traversal & NAT_T_WITH_KA)
3543 {
3544 nat_traversal_new_ka_event();
3545 }
3546
3547 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3548 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3549
3550 /* HDR* out done */
3551
3552 /* IDii out */
3553 {
3554 struct isakmp_ipsec_id id_hd;
3555 chunk_t id_b;
3556
3557 build_id_payload(&id_hd, &id_b, &st->st_connection->spd.this);
3558 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3559 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3560 || !out_chunk(id_b, &id_pbs, "my identity"))
3561 return STF_INTERNAL_ERROR;
3562 close_output_pbs(&id_pbs);
3563 }
3564
3565 /* CERT out */
3566 if (RSA_auth)
3567 {
3568 DBG(DBG_CONTROL,
3569 DBG_log("our certificate policy is %s"
3570 , enum_name(&cert_policy_names, cert_policy))
3571 )
3572 if (mycert.type != CERT_NONE)
3573 {
3574 const char *request_text = "";
3575
3576 if (cert_policy == CERT_SEND_IF_ASKED)
3577 request_text = (send_cert)? "upon request":"without request";
3578 plog("we have a cert %s sending it %s"
3579 , send_cert? "and are":"but are not", request_text);
3580 }
3581 else
3582 {
3583 plog("we don't have a cert");
3584 }
3585 }
3586 if (send_cert)
3587 {
3588 pb_stream cert_pbs;
3589
3590 struct isakmp_cert cert_hd;
3591 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3592 cert_hd.isacert_type = mycert.type;
3593
3594 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3595 return STF_INTERNAL_ERROR;
3596 if (!out_chunk(get_mycert(mycert), &cert_pbs, "CERT"))
3597 return STF_INTERNAL_ERROR;
3598 close_output_pbs(&cert_pbs);
3599 }
3600
3601 /* CR out */
3602 if (send_cr)
3603 {
3604 if (!build_and_ship_CR(mycert.type, st->st_connection->spd.that.ca
3605 , &md->rbody, ISAKMP_NEXT_SIG))
3606 return STF_INTERNAL_ERROR;
3607 }
3608
3609 /* HASH_I or SIG_I out */
3610 {
3611 u_char hash_val[MAX_DIGEST_LEN];
3612 size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3613
3614 if (auth_payload == ISAKMP_NEXT_HASH)
3615 {
3616 /* HASH_I out */
3617 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3618 , hash_val, hash_len, "HASH_I"))
3619 return STF_INTERNAL_ERROR;
3620 }
3621 else
3622 {
3623 /* SIG_I out */
3624 u_char sig_val[RSA_MAX_OCTETS];
3625 size_t sig_len = RSA_sign_hash(st->st_connection
3626 , sig_val, hash_val, hash_len);
3627
3628 if (sig_len == 0)
3629 {
3630 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3631 return STF_FAIL + AUTHENTICATION_FAILED;
3632 }
3633
3634 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3635 , &md->rbody, sig_val, sig_len, "SIG_I"))
3636 return STF_INTERNAL_ERROR;
3637 }
3638 }
3639
3640 /* encrypt message, except for fixed part of header */
3641
3642 /* st_new_iv was computed by generate_skeyids_iv */
3643 if (!encrypt_message(&md->rbody, st))
3644 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3645
3646 return STF_OK;
3647 }
3648
3649 /* Shared logic for asynchronous lookup of DNS KEY records.
3650 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3651 */
3652
3653 enum key_oppo_step {
3654 kos_null,
3655 kos_his_txt
3656 #ifdef USE_KEYRR
3657 , kos_his_key
3658 #endif
3659 };
3660
3661 struct key_continuation {
3662 struct adns_continuation ac; /* common prefix */
3663 struct msg_digest *md;
3664 enum key_oppo_step step;
3665 bool failure_ok;
3666 err_t last_ugh;
3667 };
3668
3669 typedef stf_status (key_tail_fn)(struct msg_digest *md
3670 , struct key_continuation *kc);
3671 static void
3672 report_key_dns_failure(struct id *id, err_t ugh)
3673 {
3674 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
3675
3676 (void) idtoa(id, id_buf, sizeof(id_buf));
3677 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3678 "; DNS search for KEY failed (%s)", id_buf, ugh);
3679 }
3680
3681
3682 /* Processs the Main Mode ID Payload and the Authenticator
3683 * (Hash or Signature Payload).
3684 * If a DNS query is still needed to get the other host's public key,
3685 * the query is initiated and STF_SUSPEND is returned.
3686 * Note: parameter kc is a continuation containing the results from
3687 * the previous DNS query, or NULL indicating no query has been issued.
3688 */
3689 static stf_status
3690 main_id_and_auth(struct msg_digest *md
3691 , bool initiator /* are we the Initiator? */
3692 , cont_fn_t cont_fn /* continuation function */
3693 , const struct key_continuation *kc /* current state, can be NULL */
3694 )
3695 {
3696 struct state *st = md->st;
3697 u_char hash_val[MAX_DIGEST_LEN];
3698 size_t hash_len;
3699 struct id peer;
3700 stf_status r = STF_OK;
3701
3702 /* ID Payload in */
3703 if (!decode_peer_id(md, &peer))
3704 return STF_FAIL + INVALID_ID_INFORMATION;
3705
3706 /* Hash the ID Payload.
3707 * main_mode_hash requires idpl->cur to be at end of payload
3708 * so we temporarily set if so.
3709 */
3710 {
3711 pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3712 u_int8_t *old_cur = idpl->cur;
3713
3714 idpl->cur = idpl->roof;
3715 hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3716 idpl->cur = old_cur;
3717 }
3718
3719 switch (st->st_oakley.auth)
3720 {
3721 case OAKLEY_PRESHARED_KEY:
3722 case XAUTHInitPreShared:
3723 case XAUTHRespPreShared:
3724 {
3725 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3726
3727 if (pbs_left(hash_pbs) != hash_len
3728 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3729 {
3730 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3731 , hash_pbs->cur, pbs_left(hash_pbs));
3732 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3733 /* XXX Could send notification back */
3734 r = STF_FAIL + INVALID_HASH_INFORMATION;
3735 }
3736 }
3737 break;
3738
3739 case OAKLEY_RSA_SIG:
3740 case XAUTHInitRSA:
3741 case XAUTHRespRSA:
3742 r = RSA_check_signature(&peer, st, hash_val, hash_len
3743 , &md->chain[ISAKMP_NEXT_SIG]->pbs
3744 #ifdef USE_KEYRR
3745 , kc == NULL? NULL : kc->ac.keys_from_dns
3746 #endif /* USE_KEYRR */
3747 , kc == NULL? NULL : kc->ac.gateways_from_dns
3748 );
3749
3750 if (r == STF_SUSPEND)
3751 {
3752 /* initiate/resume asynchronous DNS lookup for key */
3753 struct key_continuation *nkc
3754 = alloc_thing(struct key_continuation, "key continuation");
3755 enum key_oppo_step step_done = kc == NULL? kos_null : kc->step;
3756 err_t ugh = NULL;
3757
3758 /* Record that state is used by a suspended md */
3759 passert(st->st_suspended_md == NULL);
3760 st->st_suspended_md = md;
3761
3762 nkc->failure_ok = FALSE;
3763 nkc->md = md;
3764
3765 switch (step_done)
3766 {
3767 case kos_null:
3768 /* first try: look for the TXT records */
3769 nkc->step = kos_his_txt;
3770 #ifdef USE_KEYRR
3771 nkc->failure_ok = TRUE;
3772 #endif
3773 ugh = start_adns_query(&peer
3774 , &peer /* SG itself */
3775 , T_TXT
3776 , cont_fn
3777 , &nkc->ac);
3778 break;
3779
3780 #ifdef USE_KEYRR
3781 case kos_his_txt:
3782 /* second try: look for the KEY records */
3783 nkc->step = kos_his_key;
3784 ugh = start_adns_query(&peer
3785 , NULL /* no sgw for KEY */
3786 , T_KEY
3787 , cont_fn
3788 , &nkc->ac);
3789 break;
3790 #endif /* USE_KEYRR */
3791
3792 default:
3793 bad_case(step_done);
3794 }
3795
3796 if<