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