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