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