1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
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>.
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
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/time.h> /* for gettimeofday */
32 #include "constants.h"
38 #include "connections.h" /* needs id.h */
39 #include "preshared.h"
41 #include "demux.h" /* needs packet.h */
42 #include "adns.h" /* needs <resolv.h> */
43 #include "dnskey.h" /* needs preshared.h and adns.h */
51 #include "ipsec_doi.h" /* needs demux.h and state.h */
57 #include "crypto.h" /* requires sha1.h and md5.h */
59 #include "kernel_alg.h"
65 #include "nat_traversal.h"
71 static bool encrypt_message(pb_stream *pbs, struct state *st); /* forward declaration */
73 typedef stf_status initiator_function(
76 struct state *predecessor,
80 /* MAGIC: perform f, a function that returns notification_t
81 * and return from the ENCLOSING stf_status returning function if it fails.
83 #define RETURN_STF_FAILURE(f) \
84 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
86 static void dpd_init(struct state *st);
88 /* create output HDR as replica of input HDR */
90 echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
92 struct isakmp_hdr r_hdr = md->hdr; /* mostly same as incoming header */
94 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
96 r_hdr.isa_flags |= ISAKMP_FLAG_ENCRYPTION;
97 /* some day, we may have to set r_hdr.isa_version */
99 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
100 impossible(); /* surely must have room and be well-formed */
103 /* Compute DH shared secret from our local secret and the peer's public value.
104 * We make the leap that the length should be that of the group
105 * (see quoted passage at start of ACCEPT_KE).
108 compute_dh_shared(struct state *st, const chunk_t g
109 , const struct oakley_group_desc *group)
111 MP_INT mp_g, mp_shared;
112 struct timeval tv0, tv1;
113 unsigned long tv_diff;
115 gettimeofday(&tv0, NULL);
116 passert(st->st_sec_in_use);
117 n_to_mpz(&mp_g, g.ptr, g.len);
118 mpz_init(&mp_shared);
119 mpz_powm(&mp_shared, &mp_g, &st->st_sec, group->modulus);
121 freeanychunk(st->st_shared); /* happens in odd error cases */
122 st->st_shared = mpz_to_n(&mp_shared, group->bytes);
123 mpz_clear(&mp_shared);
124 gettimeofday(&tv1, NULL);
125 tv_diff=(tv1.tv_sec - tv0.tv_sec) * 1000000 + (tv1.tv_usec - tv0.tv_usec);
127 DBG_log("%s(): time elapsed (%s): %ld usec"
129 , enum_show(&oakley_group_names, st->st_oakley.group->group)
134 /* if took more than 200 msec ... */
135 if (tv_diff > 200000) {
136 loglog(RC_LOG_SERIOUS, "WARNING: " __FUNCTION__ "(): for %s took "
138 , enum_show(&oakley_group_names, st->st_oakley.group->group)
143 #ifdef DODGE_DH_MISSING_ZERO_BUG
144 if (st->st_shared.ptr[0] == 0)
145 loglog(RC_LOG_SERIOUS, "shared DH secret has leading zero -- triggers Pluto 1.0 bug");
147 DBG_cond_dump_chunk(DBG_CRYPT, "DH shared secret:\n", st->st_shared);
150 /* needed for PGPnet Vendor ID */
151 char pgp_vid[] = "OpenPGP10171";
153 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
154 * the corresponding public value (g). This is emitted as a KE payload.
155 * KLUDGE: if DODGE_DH_MISSING_ZERO_BUG and we're the responder,
156 * this routine computes the shared secret to see if it would
157 * have a leading zero. If so, we try again.
160 build_and_ship_KE(struct state *st, chunk_t *g
161 , const struct oakley_group_desc *group, pb_stream *outs, u_int8_t np)
163 if (!st->st_sec_in_use)
165 u_char tmp[LOCALSECRETSIZE];
168 get_rnd_bytes(tmp, LOCALSECRETSIZE);
169 st->st_sec_in_use = TRUE;
170 n_to_mpz(&st->st_sec, tmp, LOCALSECRETSIZE);
173 mpz_powm(&mp_g, &groupgenerator, &st->st_sec, group->modulus);
174 freeanychunk(*g); /* happens in odd error cases */
175 *g = mpz_to_n(&mp_g, group->bytes);
177 #ifdef DODGE_DH_MISSING_ZERO_BUG
180 /* generate a new secret to avoid this situation */
181 loglog(RC_LOG_SERIOUS, "regenerating DH private secret to avoid Pluto 1.0 bug"
182 " handling public value with leading zero");
183 mpz_clear(&st->st_sec);
184 st->st_sec_in_use = FALSE;
185 return build_and_ship_KE(st, g, group, outs, np);
187 /* if we're the responder, we can compute the shared secret
188 * to see if it would turn out OK.
194 compute_dh_shared(st, st->st_gi
195 , IS_PHASE1(st->st_state)
196 ? st->st_oakley.group : st->st_pfs_group);
199 for (i = 0; i < st->st_shared.len; i++) {
200 if (st->st_shared.ptr[i] != 0) {
209 } else if (st->st_shared.ptr[0] == 0) {
210 /* generate a new secret to avoid this situation */
211 loglog(RC_LOG_SERIOUS, "regenerating DH private secret to avoid Pluto 1.0 bug"
212 " handling shared secret with leading zero");
213 freeanychunk(st->st_shared);
214 mpz_clear(&st->st_sec);
215 st->st_sec_in_use = FALSE;
216 return build_and_ship_KE(st, g, group, outs, np);
222 DBG_dump("Local DH secret:\n", tmp, LOCALSECRETSIZE);
223 DBG_dump_chunk("Public DH value sent:\n", *g));
225 return out_generic_chunk(np, &isakmp_keyex_desc, outs, *g, "keyex value");
230 * Check and accept DH public value (Gi or Gr) from peer's message.
231 * According to RFC2409 "The Internet key exchange (IKE)" 5:
232 * The Diffie-Hellman public value passed in a KE payload, in either
233 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
234 * Diffie-Hellman group enforced, if necessary, by pre-pending the
236 * ??? For now, if DODGE_DH_MISSING_ZERO_BUG is defined, we accept shorter
237 * values to interoperate with old Plutos. This should change some day.
239 static notification_t
240 accept_KE(chunk_t *dest, const char *val_name
241 , const struct oakley_group_desc *gr
244 if (pbs_left(pbs) != gr->bytes)
246 loglog(RC_LOG_SERIOUS, "KE has %u byte DH public value; %u required"
247 , (unsigned) pbs_left(pbs), (unsigned) gr->bytes);
248 #ifdef DODGE_DH_MISSING_ZERO_BUG
249 if (pbs_left(pbs) > gr->bytes)
251 return INVALID_KEY_INFORMATION;
253 clonereplacechunk(*dest, pbs->cur, pbs_left(pbs), val_name);
254 DBG_cond_dump_chunk(DBG_CRYPT, "DH public value received:\n", *dest);
255 return NOTHING_WRONG;
260 * Check and accept optional Quick Mode KE payload for PFS.
261 * Extends ACCEPT_PFS to check whether KE is allowed or required.
263 static notification_t
264 accept_PFS_KE(struct msg_digest *md, chunk_t *dest
265 , const char *val_name, const char *msg_name)
267 struct state *st = md->st;
268 struct payload_digest *const ke_pd = md->chain[ISAKMP_NEXT_KE];
272 if (st->st_pfs_group != NULL)
274 loglog(RC_LOG_SERIOUS, "missing KE payload in %s message", msg_name);
275 return INVALID_KEY_INFORMATION;
280 if (st->st_pfs_group == NULL)
282 loglog(RC_LOG_SERIOUS, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
284 return INVALID_KEY_INFORMATION;
286 if (ke_pd->next != NULL)
288 loglog(RC_LOG_SERIOUS, "%s message contains several KE payloads; we accept at most one", msg_name);
289 return INVALID_KEY_INFORMATION; /* ??? */
291 return accept_KE(dest, val_name, st->st_pfs_group, &ke_pd->pbs);
293 return NOTHING_WRONG;
297 build_and_ship_nonce(chunk_t *n, pb_stream *outs, u_int8_t np
300 setchunk(*n, alloc_bytes(DEFAULT_NONCE_SIZE, name), DEFAULT_NONCE_SIZE);
301 get_rnd_bytes(n->ptr, DEFAULT_NONCE_SIZE);
302 return out_generic_chunk(np, &isakmp_nonce_desc, outs, *n, name);
306 * Send a notification to the peer. We could make a decision on
307 * whether to send the notification, based on the type and the
308 * destination, if we care to.
309 * It doesn't handle DELETE notifications (see send_ipsec_delete)
312 send_notification(struct state *sndst, u_int16_t type, struct state *encst,
313 msgid_t msgid, u_char *icookie, u_char *rcookie,
314 u_char *spi, size_t spisize, u_char protoid)
317 pb_stream pbs, r_hdr_pbs;
318 u_char *r_hashval, *r_hash_start;
320 passert((sndst) && (sndst->st_connection));
322 log("sending %snotification %s to %s:%u",
323 encst ? "encrypted " : "",
324 enum_name(&ipsec_notification_names, type),
325 ip_str(&sndst->st_connection->that.host_addr),
326 (unsigned)sndst->st_connection->that.host_port);
328 memset(buffer, 0, sizeof(buffer));
329 init_pbs(&pbs, buffer, sizeof(buffer), "notification msg");
333 struct isakmp_hdr hdr;
335 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
336 hdr.isa_np = encst ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_N;
337 hdr.isa_xchg = ISAKMP_XCHG_INFO;
338 hdr.isa_msgid = msgid;
339 hdr.isa_flags = encst ? ISAKMP_FLAG_ENCRYPTION : 0;
341 memcpy(hdr.isa_icookie, icookie, COOKIE_SIZE);
343 memcpy(hdr.isa_rcookie, rcookie, COOKIE_SIZE);
344 if (!out_struct(&hdr, &isakmp_hdr_desc, &pbs, &r_hdr_pbs))
348 /* HASH -- value to be filled later */
352 if (!out_generic(ISAKMP_NEXT_N, &isakmp_hash_desc, &r_hdr_pbs,
355 r_hashval = hash_pbs.cur; /* remember where to plant value */
358 encst->st_oakley.hasher->hash_digest_size,
360 encst->st_oakley.hasher->hash_digest_len,
362 &hash_pbs, "HASH(1)"))
364 close_output_pbs(&hash_pbs);
365 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
368 /* Notification Payload */
371 struct isakmp_notification isan;
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;
379 if (!out_struct(&isan, &isakmp_notification_desc, &r_hdr_pbs, ¬_pbs)
380 || !out_raw(spi, spisize, ¬_pbs, "spi"))
382 close_output_pbs(¬_pbs);
385 /* calculate hash value and patch into Hash Payload */
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);
396 DBG_log("HASH(1) computed:");
397 DBG_dump("", r_hashval, ctx.hmac_digest_size);
402 DBG_log("HASH(1) computed:");
403 DBG_dump("", r_hashval, ctx.hmac_digest_len);
408 /* Encrypt message (preserve st_iv) */
411 u_char old_iv[MAX_DIGEST_LEN];
412 if (encst->st_iv_len > MAX_DIGEST_LEN)
414 memcpy(old_iv, encst->st_iv, encst->st_iv_len);
415 init_phase2_iv(encst, &msgid);
416 if (!encrypt_message(&r_hdr_pbs, encst))
418 memcpy(encst->st_iv, old_iv, encst->st_iv_len);
422 close_output_pbs(&r_hdr_pbs);
425 /* Send packet (preserve st_tpacket) */
427 chunk_t saved_tpacket = sndst->st_tpacket;
429 setchunk(sndst->st_tpacket, pbs.start, pbs_offset(&pbs));
430 send_packet(sndst, "notification packet");
431 sndst->st_tpacket = saved_tpacket;
436 send_notification_from_state(struct state *st, enum state_kind state,
443 if (state == STATE_UNDEFINED)
444 state = st->st_state;
446 if (IS_QUICK(state)) {
447 p1st = find_phase1_state(st->st_connection, TRUE);
448 if ((p1st == NULL) || (!IS_ISAKMP_SA_ESTABLISHED(p1st->st_state))) {
449 loglog(RC_LOG_SERIOUS,
450 "no Phase1 state for Quick mode notification");
453 send_notification(st, type, p1st, generate_msgid(p1st),
454 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
456 else if (IS_ISAKMP_SA_ESTABLISHED(state)) {
457 send_notification(st, type, st, generate_msgid(st),
458 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
461 /* no ISAKMP SA established - don't encrypt notification */
462 send_notification(st, type, NULL, 0,
463 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
468 send_notification_from_md(struct msg_digest *md, u_int16_t type)
471 * Create a dummy state to be able to use send_packet in
475 * st_connection->that.host_addr
476 * st_connection->that.host_port
477 * st_connection->interface
480 struct connection cnx;
484 memset(&st, 0, sizeof(st));
485 memset(&cnx, 0, sizeof(cnx));
486 st.st_connection = &cnx;
487 cnx.that.host_addr = md->sender;
488 cnx.that.host_port = md->sender_port;
489 cnx.interface = md->iface;
491 send_notification(&st, type, NULL, 0,
492 md->hdr.isa_icookie, md->hdr.isa_rcookie, NULL, 0, PROTO_ISAKMP);
495 /* Send a Delete Notification to announce deletion of inbound IPSEC/ISAKMP SAs.
496 * Ignores states that don't have any.
497 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
500 send_delete(struct state *st)
507 ip_said said[EM_MAXRELSPIS];
510 *r_hashval, /* where in reply to jam hash value */
511 *r_hash_start; /* start of what is to be hashed */
512 bool isakmp_sa = FALSE;
514 if (IS_IPSEC_SA_ESTABLISHED(st->st_state)) {
515 p1st = find_phase1_state(st->st_connection, TRUE);
518 DBG(DBG_CONTROL, DBG_log("no Phase 1 state for Delete"));
522 if (st->st_ah.present)
524 ns->spi = st->st_ah.our_spi;
525 ns->dst = st->st_connection->this.host_addr;
526 ns->proto = PROTO_IPSEC_AH;
529 if (st->st_esp.present)
531 ns->spi = st->st_esp.our_spi;
532 ns->dst = st->st_connection->this.host_addr;
533 ns->proto = PROTO_IPSEC_ESP;
537 passert(ns != said); /* there must be some SAs to delete */
539 else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
544 return; /* nothing to do */
547 msgid = generate_msgid(p1st);
549 memset(buffer, '\0', sizeof(buffer));
550 init_pbs(&reply_pbs, buffer, sizeof(buffer), "delete msg");
554 struct isakmp_hdr hdr;
556 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
557 hdr.isa_np = ISAKMP_NEXT_HASH;
558 hdr.isa_xchg = ISAKMP_XCHG_INFO;
559 hdr.isa_msgid = msgid;
560 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
561 memcpy(hdr.isa_icookie, p1st->st_icookie, COOKIE_SIZE);
562 memcpy(hdr.isa_rcookie, p1st->st_rcookie, COOKIE_SIZE);
563 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_pbs, &r_hdr_pbs))
567 /* HASH -- value to be filled later */
571 if (!out_generic(ISAKMP_NEXT_D, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
573 r_hashval = hash_pbs.cur; /* remember where to plant value */
574 if (!out_zero(p1st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH(1)"))
576 close_output_pbs(&hash_pbs);
577 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
580 /* Delete Payloads */
583 struct isakmp_delete isad;
584 u_char isakmp_spi[2*COOKIE_SIZE];
586 isad.isad_doi = ISAKMP_DOI_IPSEC;
587 isad.isad_np = ISAKMP_NEXT_NONE;
588 isad.isad_spisize = (2 * COOKIE_SIZE);
589 isad.isad_protoid = PROTO_ISAKMP;
592 memcpy(isakmp_spi, st->st_icookie, COOKIE_SIZE);
593 memcpy(isakmp_spi+COOKIE_SIZE, st->st_rcookie, COOKIE_SIZE);
595 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
596 || !out_raw(&isakmp_spi, (2*COOKIE_SIZE), &del_pbs, "delete payload"))
598 close_output_pbs(&del_pbs);
600 else while (ns != said) {
602 struct isakmp_delete isad;
605 isad.isad_doi = ISAKMP_DOI_IPSEC;
606 isad.isad_np = ns == said? ISAKMP_NEXT_NONE : ISAKMP_NEXT_D;
607 isad.isad_spisize = sizeof(ipsec_spi_t);
608 isad.isad_protoid = ns->proto;
611 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
612 || !out_raw(&ns->spi, sizeof(ipsec_spi_t), &del_pbs, "delete payload"))
614 close_output_pbs(&del_pbs);
617 /* calculate hash value and patch into Hash Payload */
620 hmac_init_chunk(&ctx, p1st->st_oakley.hasher, p1st->st_skeyid_a);
621 hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
622 hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
623 hmac_final(r_hashval, &ctx);
626 DBG_log("HASH(1) computed:");
627 DBG_dump("", r_hashval, ctx.hmac_digest_size);
631 /* Do a dance to avoid needing a new state object.
632 * We use the Phase 1 State. This is the one with right
634 * The tricky bits are:
635 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
636 * - we need to preserve (save/restore) st_tpacket.
639 u_char old_iv[MAX_DIGEST_LEN];
640 chunk_t saved_tpacket = p1st->st_tpacket;
642 memcpy(old_iv, p1st->st_iv, p1st->st_iv_len);
643 init_phase2_iv(p1st, &msgid);
645 if(!encrypt_message(&r_hdr_pbs, p1st))
648 setchunk(p1st->st_tpacket, reply_pbs.start, pbs_offset(&reply_pbs));
649 send_packet(p1st, "delete notify");
650 p1st->st_tpacket = saved_tpacket;
652 /* get back old IV for this state */
653 memcpy(p1st->st_iv, old_iv, p1st->st_iv_len);
658 accept_delete(struct state *st, struct msg_digest *md, struct payload_digest *p)
660 struct isakmp_delete *d = &(p->payload.delete);
663 struct state *dst = NULL;
666 if ((!st) && (!(md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION))) {
667 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: not encrypted");
671 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
672 /* can't happen (if msg is encrypt), but just to be sure */
673 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
674 "ISAKMP SA not established");
678 if (d->isad_nospi == 0) {
679 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: no SPI");
683 if (pbs_left(&p->pbs) != ((unsigned)d->isad_spisize * d->isad_nospi)) {
684 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: invalid size");
688 switch (d->isad_protoid) {
690 sizespi = (2*COOKIE_SIZE);
693 case PROTO_IPSEC_ESP:
694 sizespi = sizeof(ipsec_spi_t);
697 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
698 "unknown Protocol ID (%s)",
699 enum_show(&protocol_names, d->isad_protoid));
704 if (d->isad_spisize != sizespi) {
705 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
706 "bad size (%d) for Protocol (%s)",
708 enum_show(&protocol_names, d->isad_protoid));
712 for (i=0; i<d->isad_nospi; i++) {
713 spi = p->pbs.cur + (i * sizespi);
714 if (d->isad_protoid == PROTO_ISAKMP) {
718 dst = find_phase1_state_to_delete(st, spi /*iCookie*/,
719 spi+COOKIE_SIZE /*rCookie*/);
721 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
722 "deleting ISAKMP State #%lu", dst->st_serialno);
726 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
727 "ISAKMP SA not found (maybe expired)");
735 ipsec_spi_t ipsec_spi = *((ipsec_spi_t *)spi);
737 dst = find_phase2_state_to_delete(st, d->isad_protoid, ipsec_spi, &bogus);
739 struct connection *rc = dst->st_connection;
740 if ((rc) && (rc->newest_ipsec_sa == dst->st_serialno) &&
743 * Last IPSec SA for a permanent connection that we
744 * have initiated. Replace it in a few seconds.
746 * Usefull if the other peer is rebooting
748 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
749 if ((dst->st_event) &&
750 (dst->st_event->ev_type == EVENT_SA_REPLACE) &&
751 (dst->st_event->ev_time <= DELETE_SA_DELAY + now())) {
753 * Patch from Angus Lees to ignore retransmited Delete SA.
755 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
756 "already replacing IPSEC State #%lu in %d seconds",
757 dst->st_serialno, (int)(dst->st_event->ev_time - now()));
760 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
761 "replace IPSEC State #%lu in %d seconds",
762 dst->st_serialno, DELETE_SA_DELAY);
763 dst->st_margin = DELETE_SA_DELAY;
765 event_schedule(EVENT_SA_REPLACE, DELETE_SA_DELAY, dst);
769 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
770 "deleting IPSEC State #%lu", dst->st_serialno);
775 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
776 "IPSEC SA not found (%s)",
777 bogus ? "our spi - bogus implementation" : "maybe expired");
783 /* The whole message must be a multiple of 4 octets.
784 * I'm not sure where this is spelled out, but look at
785 * rfc2408 3.6 Transform Payload.
786 * Note: it talks about 4 BYTE boundaries!
789 close_message(pb_stream *pbs)
791 size_t padding = pad_up(pbs_offset(pbs), 4);
794 (void) out_zero(padding, pbs, "message padding");
795 close_output_pbs(pbs);
798 /* Initiate an Oakley Main Mode exchange.
800 * Note: this is not called from demux.c
803 main_outI1(int whack_sock
804 , struct connection *c
805 , struct state *predecessor
809 struct state *st = new_state();
810 pb_stream reply; /* not actually a reply, but you know what I mean */
813 /* set up new state */
814 st->st_connection = c;
815 set_cur_state(st); /* we must reset before exit */
816 st->st_policy = policy & ~POLICY_IPSEC_MASK;
817 st->st_whack_sock = whack_sock;
819 st->st_state = STATE_MAIN_I1;
821 get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->that.host_addr);
823 if (c->dnshostname != NULL)
827 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
828 && !sameaddr(&new_addr, &c->that.host_addr))
830 c->that.host_addr = new_addr;
832 load_preshared_secrets();
836 insert_state(st); /* needs cookies, connection, and msgid (0) */
838 if (HAS_IPSEC_POLICY(policy))
839 add_pending(dup_any(whack_sock), st, c, policy, 1
840 , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
842 if (predecessor == NULL)
843 log("initiating Main Mode");
845 log("initiating Main Mode to replace #%lu", predecessor->st_serialno);
848 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
852 struct isakmp_hdr hdr;
853 zero(&hdr); /* default to 0 */
854 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
855 hdr.isa_np = ISAKMP_NEXT_SA;
856 hdr.isa_xchg = ISAKMP_XCHG_IDPROT;
857 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
858 /* R-cookie, flags and MessageID are left zero */
860 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
863 return STF_INTERNAL_ERROR;
866 DBG(DBG_CONTROL, DBG_log("main_outI1 - 4"));
869 u_char *sa_start = rbody.cur;
870 lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
872 /* if we use an ID_KEY_ID as own ID, we assume a
873 * PGPcert peer and have to send the Vendor ID
874 * ++++ not sure, if this is an interop problem ++++++
877 int np = (c->this.id.kind == ID_KEY_ID)? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
880 int np = ISAKMP_NEXT_VID;
883 , &oakley_sadb[auth_policy >> POLICY_ISAKMP_SHIFT]
887 return STF_INTERNAL_ERROR;
889 DBG(DBG_CONTROL, DBG_log("main_outI1 - 8"));
890 /* save initiator SA for later HASH */
891 passert(st->st_p1isa.ptr == NULL); /* no leak! (MUST be first time) */
892 clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
893 , "sa in main_outI1");
896 if (c->this.id.kind == ID_KEY_ID)
898 if (!out_generic_raw(ISAKMP_NEXT_VID, &isakmp_vendor_id_desc, &rbody
899 , pgp_vid, sizeof(pgp_vid)-1, "V_ID"))
900 return STF_INTERNAL_ERROR;
904 if (nat_traversal_enabled) {
905 /* Add supported NAT-Traversal VID */
906 if (!nat_traversal_add_vid(ISAKMP_NEXT_VID, &rbody)) {
908 return STF_INTERNAL_ERROR;
914 if (!out_vendorid(ISAKMP_NEXT_NONE, &rbody, VID_MISC_DPD))
915 return STF_INTERNAL_ERROR;
917 close_message(&rbody);
918 close_output_pbs(&reply);
920 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
921 , "reply packet for main_outI1");
924 DBG(DBG_CONTROL, DBG_log("main_outI1 - 9"));
925 send_packet(st, "main_outI1");
927 /* Set up a retransmission event, half a minute henceforth */
929 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
930 DBG(DBG_CONTROL, DBG_log("main_outI1 - 10"));
931 if (predecessor != NULL)
933 update_pending(predecessor, st);
934 whack_log(RC_NEW_STATE + STATE_MAIN_I1
935 , "%s: initiate, replacing #%lu"
936 , enum_name(&state_names, st->st_state)
937 , predecessor->st_serialno);
941 DBG(DBG_CONTROL, DBG_log("main_outI1 - 11"));
942 whack_log(RC_NEW_STATE + STATE_MAIN_I1
943 , "%s: initiate", enum_name(&state_names, st->st_state));
950 /* Initiate an Oakley Aggressive Mode exchange.
951 * --> HDR, SA, KE, Ni, IDii
956 struct connection *c,
957 struct state *predecessor,
961 struct state *st = new_state();
962 pb_stream reply; /* not actually a reply, but you know what I mean */
967 /* set up new state */
968 st->st_connection = c;
969 set_cur_state(st); /* we must reset before exit */
970 st->st_policy = policy & ~POLICY_IPSEC_MASK;
971 st->st_whack_sock = whack_sock;
973 st->st_state = STATE_AGGR_I1;
975 get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->that.host_addr);
977 if (c->dnshostname != NULL)
981 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
982 && !sameaddr(&new_addr, &c->that.host_addr))
984 c->that.host_addr = new_addr;
986 load_preshared_secrets();
990 insert_state(st); /* needs cookies, connection, and msgid (0) */
992 if (HAS_IPSEC_POLICY(policy))
993 add_pending(dup_any(whack_sock), st, c, policy, 1
994 , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
995 if (predecessor == NULL)
996 log("initiating Aggressive Mode");
998 log("initiating Aggressive Mode to replace #%lu"
999 , predecessor->st_serialno);
1002 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
1006 struct isakmp_hdr hdr;
1008 zero(&hdr); /* default to 0 */
1009 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
1010 hdr.isa_np = ISAKMP_NEXT_SA;
1011 hdr.isa_xchg = ISAKMP_XCHG_AGGR;
1012 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
1013 /* R-cookie, flags and MessageID are left zero */
1015 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
1018 return STF_INTERNAL_ERROR;
1024 u_char *sa_start = rbody.cur;
1025 lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
1026 /* if we use an ID_KEY_ID as own ID, we assume a
1027 * PGPcert peer and have to send the Vendor ID
1028 * ++++ not sure, if this is an interop problem ++++++
1031 int np = (c->this.id.kind == ID_KEY_ID)? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
1033 init_st_oakley(st, auth_policy);
1035 if (st->st_connection->algorithm_p1.dhg == OAKLEY_GROUP_MODP768) {
1036 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA)
1037 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1038 sadb = &otpsk768des3sha_sadb_am;
1040 sadb = &otpsk768dessha_sadb_am;
1042 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1043 sadb = &otpsk768des3md5_sadb_am;
1045 sadb = &otpsk768desmd5_sadb_am;
1046 } else if (st->st_connection->algorithm_p1.dhg == OAKLEY_GROUP_MODP1024) {
1047 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA)
1048 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1049 sadb = &otpsk1024des3sha_sadb_am;
1051 sadb = &otpsk1024dessha_sadb_am;
1053 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1054 sadb = &otpsk1024des3md5_sadb_am;
1056 sadb = &otpsk1024desmd5_sadb_am;
1059 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA)
1060 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1061 sadb = &otpsk1536des3sha_sadb_am;
1063 sadb = &otpsk1536dessha_sadb_am;
1065 if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1066 sadb = &otpsk1536des3md5_sadb_am;
1068 sadb = &otpsk1536desmd5_sadb_am;
1071 if (!out_sa(&rbody, sadb, st, TRUE, ISAKMP_NEXT_VID))
1074 return STF_INTERNAL_ERROR;
1077 /* save initiator SA for later HASH */
1078 passert(st->st_p1isa.ptr == NULL); /* no leak! (MUST be first time) */
1079 clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
1080 , "sa in aggr_outI1");
1084 #ifdef NAT_TRAVERSAL
1085 if (nat_traversal_enabled) {
1086 /* Add supported NAT-Traversal VID */
1087 if (!nat_traversal_add_vid(ISAKMP_NEXT_VID, &rbody)) {
1089 return STF_INTERNAL_ERROR;
1095 if (!out_vendorid(ISAKMP_NEXT_KE, &rbody, VID_MISC_DPD))
1096 return STF_INTERNAL_ERROR;
1099 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group,
1100 &rbody, ISAKMP_NEXT_NONCE))
1101 return STF_INTERNAL_ERROR;
1104 if (!build_and_ship_nonce(&st->st_ni, &rbody, ISAKMP_NEXT_ID, "Ni"))
1105 return STF_INTERNAL_ERROR;
1109 struct isakmp_ipsec_id id_hd;
1113 build_id_payload(&id_hd, &id_b, &st->st_connection->this);
1114 id_hd.isaiid_np = ISAKMP_NEXT_NONE;
1115 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &rbody, &id_pbs)
1116 || !out_chunk(id_b, &id_pbs, "my identity"))
1117 return STF_INTERNAL_ERROR;
1118 close_output_pbs(&id_pbs);
1121 /* finish message */
1123 close_message(&rbody);
1124 close_output_pbs(&reply);
1126 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply),
1127 "reply packet from aggr_outI1");
1131 DBG_cond_dump(DBG_RAW, "sending:\n",
1132 st->st_tpacket.ptr, st->st_tpacket.len);
1134 send_packet(st, "aggr_outI1");
1136 /* Set up a retransmission event, half a minute henceforth */
1138 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1140 if (predecessor != NULL)
1142 update_pending(predecessor, st);
1143 whack_log(RC_NEW_STATE + STATE_AGGR_I1
1144 , "%s: initiate, replacing #%lu"
1145 , enum_name(&state_names, st->st_state)
1146 , predecessor->st_serialno);
1150 whack_log(RC_NEW_STATE + STATE_AGGR_I1,
1151 "%s: initiate", enum_name(&state_names, st->st_state));
1159 ipsecdoi_initiate(int whack_sock
1160 , struct connection *c
1163 , so_serial_t replacing)
1165 /* If there's already an ISAKMP SA established, use that and
1166 * go directly to Quick Mode.
1167 * Note: there is no way to initiate with a Road Warrior.
1169 struct state *st = find_phase1_state(c, FALSE);
1171 DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 1"));
1174 initiator_function *initiator = (LALLIN(c->policy, POLICY_AGGRESSIVE)
1175 ? aggr_outI1 : main_outI1);
1176 DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 2"));
1177 (void) initiator(whack_sock, c, NULL, policy, try);
1179 else if (HAS_IPSEC_POLICY(policy))
1181 DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 3"));
1182 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1184 /* leave our Phase 2 negotiation pending */
1185 add_pending(whack_sock, st, c, policy, try, replacing);
1189 DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 4"));
1190 /* ??? we assume that peer_nexthop_sin isn't important:
1191 * we already have it from when we negotiated the ISAKMP SA!
1192 * It isn't clear what to do with the error return.
1194 (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1199 close_any(whack_sock);
1203 /* Replace SA with a fresh one that is similar
1205 * Shares some logic with ipsecdoi_initiate, but not the same!
1206 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1207 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1208 * ISAKMP SA if needed.
1209 * - duplicate whack fd, if live.
1210 * Does not delete the old state -- someone else will do that.
1213 ipsecdoi_replace(struct state *st, unsigned long try)
1215 int whack_sock = dup_any(st->st_whack_sock);
1216 lset_t policy = st->st_policy;
1217 struct connection *c = st->st_connection;
1219 if (IS_PHASE1(st->st_state))
1221 initiator_function *initiator;
1222 passert(!HAS_IPSEC_POLICY(policy));
1223 initiator = (LALLIN(c->policy, POLICY_AGGRESSIVE)
1224 ? aggr_outI1 : main_outI1);
1225 (void) initiator(whack_sock, c, st, policy, try);
1229 /* Add features of actual old state to policy. This ensures
1230 * that rekeying doesn't downgrade security. I admit that
1231 * this doesn't capture everything.
1233 if (st->st_pfs_group != NULL)
1234 policy |= POLICY_PFS;
1235 if (st->st_ah.present)
1237 policy |= POLICY_AUTHENTICATE;
1238 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1239 policy |= POLICY_TUNNEL;
1241 if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1243 policy |= POLICY_ENCRYPT;
1244 if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1245 policy |= POLICY_TUNNEL;
1247 if (st->st_ipcomp.present)
1249 policy |= POLICY_COMPRESS;
1250 if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1251 policy |= POLICY_TUNNEL;
1253 passert(HAS_IPSEC_POLICY(policy));
1254 ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1259 /* SKEYID for preshared keys.
1260 * See draft-ietf-ipsec-ike-01.txt 4.1
1263 skeyid_preshared(struct state *st)
1265 const chunk_t *pss = get_preshared_secret(st->st_connection);
1269 loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1274 struct hmac_ctx ctx;
1276 hmac_init_chunk(&ctx, st->st_oakley.hasher, *pss);
1277 hmac_update_chunk(&ctx, st->st_ni);
1278 hmac_update_chunk(&ctx, st->st_nr);
1279 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_preshared()", &ctx);
1285 skeyid_digisig(struct state *st)
1287 struct hmac_ctx ctx;
1290 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1291 * so we have to build a temporary concatentation.
1293 nir.len = st->st_ni.len + st->st_nr.len;
1294 nir.ptr = alloc_bytes(nir.len, "Ni + Nr in skeyid_digisig");
1295 memcpy(nir.ptr, st->st_ni.ptr, st->st_ni.len);
1296 memcpy(nir.ptr+st->st_ni.len, st->st_nr.ptr, st->st_nr.len);
1297 hmac_init_chunk(&ctx, st->st_oakley.hasher, nir);
1300 hmac_update_chunk(&ctx, st->st_shared);
1301 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_digisig()", &ctx);
1305 /* Generate the SKEYID_* and new IV
1306 * See draft-ietf-ipsec-ike-01.txt 4.1
1309 generate_skeyids_iv(struct state *st)
1311 /* Generate the SKEYID */
1312 switch (st->st_oakley.auth)
1314 case OAKLEY_PRESHARED_KEY:
1315 if (!skeyid_preshared(st))
1319 case OAKLEY_RSA_SIG:
1320 if (!skeyid_digisig(st))
1324 case OAKLEY_DSS_SIG:
1327 case OAKLEY_RSA_ENC:
1328 case OAKLEY_RSA_ENC_REV:
1329 case OAKLEY_ELGAMAL_ENC:
1330 case OAKLEY_ELGAMAL_ENC_REV:
1334 exit_log("generate_skeyids_iv(): unsupported authentication method %s",
1335 enum_show(&oakley_auth_names, st->st_oakley.auth));
1338 /* generate SKEYID_* from SKEYID */
1340 struct hmac_ctx ctx;
1342 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1345 hmac_update_chunk(&ctx, st->st_shared);
1346 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1347 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1348 hmac_update(&ctx, "\0", 1);
1349 hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1353 hmac_update_chunk(&ctx, st->st_skeyid_d);
1354 hmac_update_chunk(&ctx, st->st_shared);
1355 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1356 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1357 hmac_update(&ctx, "\1", 1);
1358 hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1362 hmac_update_chunk(&ctx, st->st_skeyid_a);
1363 hmac_update_chunk(&ctx, st->st_shared);
1364 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1365 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1366 hmac_update(&ctx, "\2", 1);
1367 hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1372 union hash_ctx hash_ctx;
1373 const struct hash_desc *h = st->st_oakley.hasher;
1375 st->st_new_iv_len = h->hash_digest_size;
1376 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1379 DBG_dump_chunk("DH_i:", st->st_gi);
1380 DBG_dump_chunk("DH_r:", st->st_gr);
1382 h->hash_init(&hash_ctx);
1383 h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1384 h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1385 h->hash_final(st->st_new_iv, &hash_ctx);
1388 /* Oakley Keying Material
1389 * Derived from Skeyid_e: if it is not big enough, generate more
1391 * See draft-ietf-ipsec-isakmp-oakley-07.txt Appendix B
1394 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1395 const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1396 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1397 u_char *k = st->st_skeyid_e.ptr;
1399 if (keysize > st->st_skeyid_e.len)
1401 struct hmac_ctx ctx;
1404 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1405 hmac_update(&ctx, "\0", 1);
1408 hmac_final(&keytemp[i], &ctx);
1409 i += ctx.hmac_digest_size;
1413 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1417 clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1421 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1422 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1423 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1424 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1425 DBG_dump_chunk("enc key:", st->st_enc_key);
1426 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1430 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1431 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1432 * New Group Mode, or ISAKMP Informational Exchanges).
1433 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1434 * If hashus argument is TRUE, we're generating a hash for our end.
1435 * See RFC2409 IKE 5.
1437 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1438 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1439 * The extensive common logic is embodied in main_mode_hash_body().
1440 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1444 main_mode_hash_body(struct state *st
1445 , bool hashi /* Initiator? */
1446 , const pb_stream *idpl /* ID payload, as PBS */
1447 , union hash_ctx *ctx
1448 , void (*hash_update)(union hash_ctx *, const u_char *input, unsigned int len))
1450 #if 0 /* if desperate to debug hashing */
1451 # define hash_update(ctx, input, len) { \
1452 DBG_cond_dump(DBG_CRYPT, "hash input", input, len); \
1453 (hash_update)(ctx, input, len); \
1457 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1461 hash_update_chunk(ctx, st->st_gi);
1462 hash_update_chunk(ctx, st->st_gr);
1463 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1464 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1468 hash_update_chunk(ctx, st->st_gr);
1469 hash_update_chunk(ctx, st->st_gi);
1470 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1471 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1474 DBG(DBG_CRYPT, DBG_log("hashing %d bytes of SA"
1475 , st->st_p1isa.len - sizeof(struct isakmp_generic)));
1478 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1479 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1481 /* Hash identification payload, without generic payload header.
1482 * We used to reconstruct ID Payload for this purpose, but now
1483 * we use the bytes as they appear on the wire to avoid
1484 * "spelling problems".
1487 , idpl->start + sizeof(struct isakmp_generic)
1488 , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1490 # undef hash_update_chunk
1494 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1495 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1496 * New Group Mode, or ISAKMP Informational Exchanges).
1497 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1498 * If hashus argument is TRUE, we're generating a hash for our end.
1499 * See RFC2409 IKE 5.
1501 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1502 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1503 * The extensive common logic is embodied in main_mode_hash_body().
1504 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1508 aggr_mode_hash_body(struct state *st, bool hashi, bool hashus
1509 , union hash_ctx *ctx
1510 , void (*hash_update)(union hash_ctx *, const u_char *input, unsigned int len))
1512 #if 0 /* if desperate to debug hashing */
1513 # define hash_update(ctx, input, len) { \
1514 DBG_cond_dump(DBG_CRYPT, "hash input", input, len); \
1515 (hash_update)(ctx, input, len); \
1519 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1522 hash_update_chunk(ctx, st->st_gi);
1523 hash_update_chunk(ctx, st->st_gr);
1524 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1525 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1529 hash_update_chunk(ctx, st->st_gr);
1530 hash_update_chunk(ctx, st->st_gi);
1531 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1532 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1535 DBG(DBG_CRYPT, DBG_log("hashing %d bytes of SA"
1536 , st->st_p1isa.len - sizeof(struct isakmp_generic)));
1539 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1540 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1542 /* IDio_b (o stands for originator: i or r) */
1544 /* Hash identification payload, without generic payload header.
1545 * Note: the part of header and body used must be in network order!
1547 struct connection *c = st->st_connection;
1548 struct isakmp_ipsec_id id_hd;
1551 build_id_payload(&id_hd, &id_b, hashus? &c->this : &c->that);
1554 /* ugly feature *we* don't use */
1555 id_hd.isaiid_protoid = st->st_peeridentity_protocol;
1556 id_hd.isaiid_port = htons(st->st_peeridentity_port);
1559 DBG_log("Hashing %s ID: Type %s, Protocol %d, Port %d"
1560 , hashus? "my" : "his"
1561 , enum_show(&ident_names, id_hd.isaiid_idtype)
1562 , id_hd.isaiid_protoid, htons(id_hd.isaiid_port)));
1564 DBG_dump("ID to be hashed:"
1565 , (u_char *)&id_hd + sizeof(struct isakmp_generic)
1566 , sizeof(id_hd) - sizeof(struct isakmp_generic)));
1568 /* NOTE: hash does NOT include the generic payload part of
1572 , (u_char *)&id_hd + sizeof(struct isakmp_generic)
1573 , sizeof(id_hd) - sizeof(struct isakmp_generic));
1576 DBG_dump_chunk("ID to be hashed:", id_b));
1578 hash_update_chunk(ctx, id_b);
1580 # undef hash_update_chunk
1584 static size_t /* length of hash */
1585 main_mode_hash(struct state *st
1586 , u_char *hash_val /* resulting bytes */
1587 , bool hashi /* Initiator? */
1588 , const pb_stream *idpl) /* ID payload, as PBS; cur must be at end */
1590 struct hmac_ctx ctx;
1592 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1593 main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1594 hmac_final(hash_val, &ctx);
1595 return ctx.hmac_digest_size;
1599 aggr_mode_hash(struct state *st, u_char *hash_val
1600 , bool hashi, bool hashus)
1602 struct hmac_ctx ctx;
1604 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1605 aggr_mode_hash_body(st, hashi, hashus, &ctx.hash_ctx, ctx.h->hash_update);
1606 hmac_final(hash_val, &ctx);
1607 return ctx.hmac_digest_size;
1610 #if 0 /* only needed for DSS */
1612 main_mode_sha1(struct state *st
1613 , u_char *hash_val /* resulting bytes */
1614 , size_t *hash_len /* length of hash */
1615 , bool hashi /* Initiator? */
1616 , const pb_stream *idpl) /* ID payload, as PBS */
1620 SHA1Init(&ctx.ctx_sha1);
1621 SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1622 *hash_len = SHA1_DIGEST_SIZE;
1623 main_mode_hash_body(st, hashi, idpl, &ctx
1624 , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1625 SHA1Final(hash_val, &ctx.ctx_sha1);
1629 /* Create an RSA signature of a hash.
1630 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1631 * Use PKCS#1 version 1.5 encryption of hash (called
1632 * RSAES-PKCS1-V1_5) in PKCS#2.
1635 RSA_sign_hash(struct connection *c
1636 , u_char sig_val[RSA_MAX_OCTETS]
1637 , const u_char *hash_val, size_t hash_len)
1639 const struct RSA_private_key *k = get_RSA_private_key(c);
1641 u_char *p = sig_val;
1647 return 0; /* failure: no key to use */
1649 passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1651 DBG(DBG_CONTROL | DBG_CRYPT
1652 , DBG_log("signing hash with RSA Key *%s", k->pub.keyid));
1654 /* PKCS#1 v1.5 8.1 encryption-block formatting */
1656 *p++ = 0x01; /* BT (block type) 01 */
1657 padlen = sz - 3 - hash_len;
1658 memset(p, 0xFF, padlen);
1661 memcpy(p, hash_val, hash_len);
1662 passert(p + hash_len - sig_val == (ptrdiff_t)sz);
1664 /* PKCS#1 v1.5 8.2 octet-string-to-integer conversion */
1665 n_to_mpz(t1, sig_val, sz); /* (could skip leading 0x00) */
1667 /* PKCS#1 v1.5 8.3 RSA computation y = x^c mod n
1668 * Better described in PKCS#1 v2.0 5.1 RSADP.
1669 * There are two methods, depending on the form of the private key.
1670 * We use the one based on the Chinese Remainder Theorem.
1674 mpz_powm(t2, t1, &k->dP, &k->p); /* m1 = c^dP mod p */
1676 mpz_powm(t1, t1, &k->dQ, &k->q); /* m2 = c^dQ mod Q */
1678 mpz_sub(t2, t2, t1); /* h = qInv (m1 - m2) mod p */
1679 mpz_mod(t2, t2, &k->p);
1680 mpz_mul(t2, t2, &k->qInv);
1681 mpz_mod(t2, t2, &k->p);
1683 mpz_mul(t2, t2, &k->q); /* m = m2 + h q */
1684 mpz_add(t1, t1, t2);
1686 /* PKCS#1 v1.5 8.4 integer-to-octet-string conversion */
1687 ch = mpz_to_n(t1, sz);
1688 memcpy(sig_val, ch.ptr, sz);
1696 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1698 * As a side effect, on success, the public key is copied into the
1699 * state object to record the authenticator.
1701 * Can fail because wrong public key is used or because hash disagrees.
1702 * We distinguish because diagnostics should also.
1704 * The result is NULL if the Signature checked out.
1705 * Otherwise, the first character of the result indicates
1706 * how far along failure occurred. A greater character signifies
1710 * 0 reserved for caller
1711 * 1 SIG length doesn't match key length -- wrong key
1712 * 2-8 malformed ECB after decryption -- probably wrong key
1713 * 9 decrypted hash != computed hash -- probably correct key
1715 * Although the math should be the same for generating and checking signatures,
1716 * it is not: the knowledge of the private key allows more efficient (i.e.
1717 * different) computation for encryption.
1720 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1721 , const pb_stream *sig_pbs, const struct RSA_public_key *k
1724 const u_char *sig_val = sig_pbs->cur;
1725 size_t sig_len = pbs_left(sig_pbs);
1726 u_char s[RSA_MAX_OCTETS]; /* for decrypted sig_val */
1727 u_char *hash_in_s = &s[sig_len - hash_len];
1729 /* decrypt the signature -- reversing RSA_sign_hash */
1730 if (sig_len != k->k)
1732 /* XXX notification: INVALID_KEY_INFORMATION */
1733 return "1" "SIG length does not match public key length";
1736 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1741 n_to_mpz(c, sig_val, sig_len);
1742 mpz_powm(c, c, &k->e, &k->n);
1744 temp_s = mpz_to_n(c, sig_len); /* back to octets */
1745 memcpy(s, temp_s.ptr, sig_len);
1750 /* sanity check on signature: see if it matches
1751 * PKCS#1 v1.5 8.1 encryption-block formatting
1757 ugh = "2" "no leading 00";
1758 else if (hash_in_s[-1] != 0x00)
1759 ugh = "3" "00 separator not present";
1760 else if (s[1] == 0x01)
1764 for (p = &s[2]; p != hash_in_s - 1; p++)
1768 ugh = "4" "invalid Padding String";
1773 else if (s[1] == 0x02)
1777 for (p = &s[2]; p != hash_in_s - 1; p++)
1781 ugh = "5" "invalid Padding String";
1787 ugh = "6" "Block Type not 01 or 02";
1791 /* note: it might be a good idea to make sure that
1792 * an observer cannot tell what kind of failure happened.
1793 * I don't know what this means in practice.
1795 /* We probably selected the wrong public key for peer:
1796 * SIG Payload decrypted into malformed ECB
1798 /* XXX notification: INVALID_KEY_INFORMATION */
1803 /* We have the decoded hash: see if it matches. */
1804 if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1806 /* good: header, hash, signature, and other payloads well-formed
1807 * good: we could find an RSA Sig key for the peer.
1808 * bad: hash doesn't match
1809 * Guess: sides disagree about key to be used.
1811 DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1812 DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1813 /* XXX notification: INVALID_HASH_INFORMATION */
1814 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1817 /* Success: copy successful key into state.
1818 * There might be an old one if we previously aborted this
1821 free_public_keys(&st->st_peer_pubkey);
1822 st->st_peer_pubkey = public_key_from_rsa(k);
1824 return NULL; /* happy happy */
1827 /* Check signature against all RSA public keys we can find.
1828 * If we need keys from DNS KEY records, and they haven't been fetched,
1829 * return STF_SUSPEND to ask for asynch DNS lookup.
1831 * take_a_crack is a helper function. Mostly forensic.
1832 * If only we had coroutines.
1835 /* RSA_check_signature's args that take_a_crack needs */
1837 const u_char *hash_val;
1839 const pb_stream *sig_pbs;
1841 /* state carried between calls */
1842 err_t best_ugh; /* most successful failure */
1843 int tried_cnt; /* number of keys tried */
1844 char tried[50]; /* keyids of tried public keys */
1845 char *tn; /* roof of tried[] */
1849 take_a_crack(struct tac_state *s
1850 , const struct RSA_public_key *k
1851 , const char *story)
1853 err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1859 DBG(DBG_CRYPT | DBG_CONTROL
1860 , DBG_log("an RSA Sig check passed with *%s [%s]"
1861 , k->keyid, story));
1867 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1868 , ugh + 1, k->keyid, story));
1869 if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1872 && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1874 strcpy(s->tn, " *");
1875 strcpy(s->tn + 2, k->keyid);
1876 s->tn += strlen(s->tn);
1883 RSA_check_signature(struct state *st
1884 , const u_char hash_val[MAX_DIGEST_LEN]
1886 , const pb_stream *sig_pbs)
1888 const struct connection *c = st->st_connection;
1890 err_t dns_ugh = NULL;
1893 s.hash_val = hash_val;
1894 s.hash_len = hash_len;
1895 s.sig_pbs = sig_pbs;
1901 /* try all gateway records hung off c */
1902 if ((c->policy & POLICY_OPPO))
1906 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1908 /* only consider entries that have a key and are for our peer */
1909 if (gw->gw_key_present
1910 && same_id(&gw->gw_id, &c->that.id)
1911 && take_a_crack(&s, &gw->gw_key, "key saved from DNS TXT"))
1916 /* try all appropriate Public keys */
1918 struct pubkeyrec *p, **pp;
1922 for (p = pubkeys; p != NULL; p = *pp)
1924 if (p->alg == PUBKEY_ALG_RSA && same_id(&c->that.id, &p->id))
1928 /* check if found public key has expired */
1930 if (p->until != UNDEFINED_TIME && p->until < now)
1932 loglog(RC_LOG_SERIOUS,
1933 "cached RSA public key has expired and has been deleted");
1934 *pp = free_public_key(p);
1935 continue; /* continue with next public key */
1938 if (take_a_crack(&s, &p->u.rsa, "preloaded key"))
1945 /* if no key was found (evidenced by best_ugh == NULL)
1946 * and this connection is opportunistic,
1947 * then go search DNS for keys for peer.
1949 if (s.best_ugh == NULL && (c->policy & POLICY_OPPO))
1951 struct pubkeyrec *kr;
1953 if (keys_from_dns == NULL)
1954 return STF_SUSPEND; /* ask for asynch DNS lookup */
1956 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1958 if (kr->alg == PUBKEY_ALG_RSA)
1960 if (take_a_crack(&s, &kr->u.rsa, "key from DNS KEY"))
1962 free_public_keys(&keys_from_dns);
1968 free_public_keys(&keys_from_dns);
1971 /* no acceptable key was found: diagnose */
1973 char id_buf[IDTOA_BUF]; /* arbitrary limit on length of ID reported */
1975 (void) idtoa(&st->st_connection->that.id, id_buf, sizeof(id_buf));
1977 if (s.best_ugh == NULL)
1979 if (dns_ugh == NULL)
1980 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1983 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1984 "; DNS search for KEY failed (%s)"
1987 /* ??? is this the best code there is? */
1988 return STF_FAIL + INVALID_KEY_INFORMATION;
1991 if (s.best_ugh[0] == '9')
1993 loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1994 return STF_FAIL + INVALID_HASH_INFORMATION;
1998 if (s.tried_cnt == 1)
2000 loglog(RC_LOG_SERIOUS
2001 , "Signature check (on %s) failed (wrong key?); tried%s"
2004 DBG_log("public key for %s failed:"
2005 " decrypted SIG payload into a malformed ECB (%s)"
2006 , id_buf, s.best_ugh + 1));
2010 loglog(RC_LOG_SERIOUS
2011 , "Signature check (on %s) failed:"
2012 " tried%s keys but none worked."
2015 DBG_log("all %d public keys for %s failed:"
2016 " best decrypted SIG payload into a malformed ECB (%s)"
2017 , s.tried_cnt, id_buf, s.best_ugh + 1));
2019 return STF_FAIL + INVALID_KEY_INFORMATION;
2026 * This macro is magic -- it cannot be expressed as a function.
2027 * - it causes the caller to return!
2028 * - it declares local variables and expects the "do_hash" argument
2029 * expression to reference them (hash_val, hash_pbs)
2031 #define CHECK_QUICK_HASH(md, do_hash, hash_name, msg_name) { \
2032 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs; \
2033 u_char hash_val[MAX_DIGEST_LEN]; \
2034 size_t hash_len = do_hash; \
2035 if (pbs_left(hash_pbs) != hash_len \
2036 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0) \
2038 DBG_cond_dump(DBG_CRYPT, "received " hash_name ":", hash_pbs->cur, pbs_left(hash_pbs)); \
2039 loglog(RC_LOG_SERIOUS, "received " hash_name " does not match computed value in " msg_name); \
2040 return STF_FAIL + INVALID_HASH_INFORMATION; \
2044 static notification_t
2045 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
2047 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
2048 size_t len = pbs_left(nonce_pbs);
2050 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
2052 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
2053 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
2054 return PAYLOAD_MALFORMED; /* ??? */
2056 clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
2057 return NOTHING_WRONG;
2060 /* START_HASH_PAYLOAD
2062 * Emit a to-be-filled-in hash payload, noting the field start (r_hashval)
2063 * and the start of the part of the message to be hashed (r_hash_start).
2064 * This macro is magic.
2065 * - it can cause the caller to return
2066 * - it references variables local to the caller (r_hashval, r_hash_start, st)
2068 #define START_HASH_PAYLOAD(rbody, np) { \
2069 pb_stream hash_pbs; \
2070 if (!out_generic(np, &isakmp_hash_desc, &(rbody), &hash_pbs)) \
2071 return STF_INTERNAL_ERROR; \
2072 r_hashval = hash_pbs.cur; /* remember where to plant value */ \
2073 if (!out_zero(st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH")) \
2074 return STF_INTERNAL_ERROR; \
2075 close_output_pbs(&hash_pbs); \
2076 r_hash_start = (rbody).cur; /* hash from after HASH payload */ \
2079 /* encrypt message, sans fixed part of header
2080 * IV is fetched from st->st_new_iv and stored into st->st_iv.
2081 * The theory is that there will be no "backing out", so we commit to IV.
2082 * We also close the pbs.
2085 encrypt_message(pb_stream *pbs, struct state *st)
2087 const struct encrypt_desc *e = st->st_oakley.encrypter;
2088 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
2089 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
2091 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
2093 /* Pad up to multiple of encryption blocksize.
2094 * See the description associated with the definition of
2095 * struct isakmp_hdr in packet.h.
2098 size_t padding = pad_up(enc_len, e->enc_blocksize);
2102 if (!out_zero(padding, pbs, "encryption padding"))
2108 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
2109 /* e->crypt(TRUE, enc_start, enc_len, st); */
2110 crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
2113 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
2118 /* Compute HASH(1), HASH(2) of Quick Mode.
2119 * HASH(1) is part of Quick I1 message.
2120 * HASH(2) is part of Quick R1 message.
2121 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
2122 * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
2125 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
2126 , const struct state *st, const msgid_t *msgid, bool hash2)
2128 struct hmac_ctx ctx;
2130 #if 0 /* if desperate to debug hashing */
2131 # define hmac_update(ctx, ptr, len) { \
2132 DBG_dump("hash input", (ptr), (len)); \
2133 (hmac_update)((ctx), (ptr), (len)); \
2135 DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
2137 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
2138 hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
2140 hmac_update_chunk(&ctx, st->st_ni); /* include Ni_b in the hash */
2141 hmac_update(&ctx, start, roof-start);
2142 hmac_final(dest, &ctx);
2145 DBG_log("HASH(%d) computed:", hash2 + 1);
2146 DBG_dump("", dest, ctx.hmac_digest_size));
2147 return ctx.hmac_digest_size;
2151 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
2152 * Used by: quick_inR1_outI2, quick_inI2
2153 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
2154 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
2155 * Message ID and Nonces. This is a mistake.
2158 quick_mode_hash3(u_char *dest, struct state *st)
2160 struct hmac_ctx ctx;
2162 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
2163 hmac_update(&ctx, "\0", 1);
2164 hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
2165 hmac_update_chunk(&ctx, st->st_ni);
2166 hmac_update_chunk(&ctx, st->st_nr);
2167 hmac_final(dest, &ctx);
2168 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
2169 return ctx.hmac_digest_size;
2172 /* Compute Phase 2 IV.
2173 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
2176 init_phase2_iv(struct state *st, const msgid_t *msgid)
2178 const struct hash_desc *h = st->st_oakley.hasher;
2181 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
2182 , st->st_iv, st->st_iv_len);
2184 st->st_new_iv_len = h->hash_digest_size;
2185 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
2188 h->hash_update(&ctx, st->st_iv, st->st_iv_len);
2189 passert(*msgid != 0);
2190 h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
2191 h->hash_final(st->st_new_iv, &ctx);
2193 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
2194 , st->st_new_iv, st->st_new_iv_len);
2197 /* Initiate quick mode.
2198 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
2199 * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
2200 * Note: this is not called from demux.c
2204 emit_subnet_id(ip_subnet *net
2205 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
2207 struct isakmp_ipsec_id id;
2210 const unsigned char *tbp;
2214 id.isaiid_idtype = aftoinfo(subnettypeof(net))->id_subnet;
2215 id.isaiid_protoid = protoid;
2216 id.isaiid_port = port;
2218 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
2221 networkof(net, &ta);
2222 tal = addrbytesptr(&ta, &tbp);
2223 if (!out_raw(tbp, tal, &id_pbs, "client network"))
2227 tal = addrbytesptr(&ta, &tbp);
2228 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2231 close_output_pbs(&id_pbs);
2236 quick_outI1(int whack_sock
2237 , struct state *isakmp_sa
2238 , struct connection *c
2241 , so_serial_t replacing)
2243 struct state *st = duplicate_state(isakmp_sa);
2244 pb_stream reply; /* not really a reply */
2246 u_char /* set by START_HASH_PAYLOAD: */
2247 *r_hashval, /* where in reply to jam hash value */
2248 *r_hash_start; /* start of what is to be hashed */
2249 bool has_client = c->this.has_client || c->that.has_client;
2251 st->st_whack_sock = whack_sock;
2252 st->st_connection = c;
2253 set_cur_state(st); /* we must reset before exit */
2254 st->st_policy = policy;
2257 st->st_myuserprotoid = st->st_peeruserprotoid = 0;
2258 st->st_myuserport = st->st_peeruserport = 0;
2260 st->st_msgid = generate_msgid(isakmp_sa);
2261 st->st_state = STATE_QUICK_I1;
2263 if (c->dnshostname != NULL)
2265 ip_address new_addr;
2267 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
2268 && !sameaddr(&new_addr, &c->that.host_addr))
2270 c->that.host_addr = new_addr;
2272 load_preshared_secrets();
2276 insert_state(st); /* needs cookies, connection, and msgid */
2278 if (replacing == SOS_NOBODY)
2279 log("initiating Quick Mode %s"
2280 , bitnamesof(sa_policy_bit_names, policy));
2282 log("initiating Quick Mode %s to replace #%lu"
2283 , bitnamesof(sa_policy_bit_names, policy), replacing);
2285 #ifdef NAT_TRAVERSAL
2286 if (isakmp_sa->nat_traversal & NAT_T_DETECTED) {
2287 /* Duplicate nat_traversal status in new state */
2288 st->nat_traversal = isakmp_sa->nat_traversal;
2289 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)) {
2292 nat_traversal_change_port_lookup(NULL, st);
2295 st->nat_traversal = 0;
2300 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2304 struct isakmp_hdr hdr;
2306 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2307 hdr.isa_np = ISAKMP_NEXT_HASH;
2308 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2309 hdr.isa_msgid = st->st_msgid;
2310 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2311 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2312 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2313 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2316 return STF_INTERNAL_ERROR;
2320 /* HASH(1) -- create and note space to be filled later */
2321 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2325 /* If PFS specified, use the same group as during Phase 1:
2326 * since no negotiation is possible, we pick one that is
2327 * very likely supported.
2329 if (st->st_connection->alg_info_esp && st->st_connection->alg_info_esp->esp_pfsgroup)
2330 st->st_pfs_group = lookup_group(st->st_connection->alg_info_esp->esp_pfsgroup);
2331 if (!st->st_pfs_group)
2332 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2334 /* Emit SA payload based on a subset of the policy bits.
2335 * POLICY_COMPRESS is considered iff we can do IPcomp.
2338 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2341 pm |= POLICY_COMPRESS;
2344 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2345 , st, FALSE, ISAKMP_NEXT_NONCE))
2348 return STF_INTERNAL_ERROR;
2353 if (!build_and_ship_nonce(&st->st_ni, &rbody
2354 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE
2358 return STF_INTERNAL_ERROR;
2361 /* [ KE ] out (for PFS) */
2363 if (st->st_pfs_group != NULL)
2365 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2366 , &rbody, has_client? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE))
2369 return STF_INTERNAL_ERROR;
2373 /* [ IDci, IDcr ] out */
2376 /* IDci (we are initiator), then IDcr (peer is responder) */
2377 if (!emit_subnet_id(&c->this.client
2378 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2379 || !emit_subnet_id(&c->that.client
2380 , ISAKMP_NEXT_NONE, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2383 return STF_INTERNAL_ERROR;
2387 #ifdef NAT_TRAVERSAL
2388 if ((st->nat_traversal & NAT_T_WITH_NATOA) &&
2389 (!(st->st_policy & POLICY_TUNNEL)) &&
2390 (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))) {
2391 /** Send NAT-OA if our address is NATed */
2392 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st)) {
2394 return STF_INTERNAL_ERROR;
2399 /* finish computing HASH(1), inserting it in output */
2400 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2401 , st, &st->st_msgid, FALSE);
2403 /* encrypt message, except for fixed part of header */
2405 init_phase2_iv(isakmp_sa, &st->st_msgid);
2406 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2407 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2409 if (!encrypt_message(&rbody, st))
2412 return STF_INTERNAL_ERROR;
2415 /* save packet, now that we know its size */
2416 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2417 , "reply packet from quick_outI1");
2419 /* send the packet */
2421 send_packet(st, "quick_outI1");
2424 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2426 if (replacing == SOS_NOBODY)
2427 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2429 , enum_name(&state_names, st->st_state));
2431 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2432 , "%s: initiate to replace #%lu"
2433 , enum_name(&state_names, st->st_state)
2441 * Decode the CERT payload of Phase 1.
2444 decode_cert(struct msg_digest *md)
2446 struct payload_digest *p;
2448 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2450 struct isakmp_cert *const cert = &p->payload.cert;
2452 blob.ptr = p->pbs.cur;
2453 blob.len = pbs_left(&p->pbs);
2454 if (cert->isacert_type == CERT_X509_SIGNATURE)
2456 x509cert_t cert = empty_x509cert;
2457 if (parse_x509cert(blob, 0, &cert))
2459 if (verify_x509cert(&cert))
2462 DBG_log("Public key validated")
2464 add_x509_public_key(&cert, DAL_SIGNED);
2468 log("X.509 certificate rejected");
2470 free_generalNames(cert.subjectAltName);
2471 free_generalNames(cert.crlDistributionPoints);
2474 log("Error in X.509 certificate");
2476 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2478 x509cert_t *cert = NULL;
2480 if (parse_pkcs7_cert(blob, &cert))
2481 store_x509certs(&cert);
2483 log("Error in PKCS#7 wrapped X.509 certificates");
2487 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2488 enum_show(&cert_type_names, cert->isacert_type));
2489 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2495 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2496 * Note: we may change connections as a result.
2497 * We must be called before SIG or HASH are decoded since we
2498 * may change the peer's RSA key or ID.
2501 decode_peer_id(struct msg_digest *md, bool initiator, bool aggrmode)
2503 struct state *const st = md->st;
2504 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2505 pb_stream *const id_pbs = &id_pld->pbs;
2506 struct isakmp_id *const id = &id_pld->payload.id;
2509 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2510 * It talks about the protocol ID and Port fields of the ID
2511 * Payload, but they don't exist as such in Phase 1.
2512 * We use more appropriate names.
2513 * isaid_doi_specific_a is in place of Protocol ID.
2514 * isaid_doi_specific_b is in place of Port.
2515 * Besides, there is no good reason for allowing these to be
2516 * other than 0 in Phase 1.
2518 #ifdef NAT_TRAVERSAL
2519 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING) &&
2520 (id->isaid_doi_specific_a == IPPROTO_UDP) &&
2521 ((id->isaid_doi_specific_b == 0) || (id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))) {
2522 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2523 "accepted with port_floating NAT-T",
2524 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2528 if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2529 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2531 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2533 , IPPROTO_UDP, IKE_UDP_PORT
2534 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2538 /* XXX Check for valid ID types? */
2539 peer.kind = id->isaid_idtype;
2545 /* failure mode for initaddr is probably inappropriate address length */
2547 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2548 , peer.kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2553 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2554 , enum_show(&ident_names, peer.kind), ugh);
2561 #ifndef INTEROP_CHECKPOINT_FW_4_1
2562 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2564 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2570 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2572 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2573 , enum_show(&ident_names, peer.kind));
2577 /* ??? ought to do some more sanity check, but what? */
2579 setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2583 setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2585 DBG_dump_chunk("KEY ID:", peer.name));
2588 case ID_DER_ASN1_DN:
2589 setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2591 DBG_dump_chunk("DER ASN1 DN:", peer.name));
2595 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2597 , enum_show(&ident_names, peer.kind)
2598 , inet_ntoa(md->sin.sin_addr));
2602 /* crazy stuff, must be kept for hash */
2603 st->st_peeridentity_protocol = id->isaid_doi_specific_a;
2604 st->st_peeridentity_port = id->isaid_doi_specific_b;
2608 char buf[IDTOA_BUF];
2610 idtoa(&peer, buf, sizeof(buf));
2611 DBG_log("%s Mode peer's ID is %s: '%s'",
2612 aggrmode ? "Aggressive" : "Main",
2613 enum_show(&ident_names, id->isaid_idtype),
2615 log("Peer ID is %s: '%s'",
2616 enum_show(&ident_names, id->isaid_idtype), buf);
2619 /* check for certificates */
2622 /* Now that we've decoded the ID payload, let's see if we
2623 * need to switch connections.
2624 * We must not switch horses if we initiated:
2625 * - if the initiation was explicit, we'd be ignoring user's intent
2626 * - if opportunistic, we'll lose our HOLD info
2630 if (!same_id(&st->st_connection->that.id, &peer))
2632 char expect[IDTOA_BUF]
2635 idtoa(&st->st_connection->that.id, expect, sizeof(expect));
2636 idtoa(&peer, found, sizeof(found));
2637 loglog(RC_LOG_SERIOUS
2638 , "we require peer to have ID '%s', but peer declares '%s'"
2645 struct connection *c = st->st_connection;
2646 struct connection *r = refine_host_connection(st, &peer, initiator, aggrmode);
2650 char buf[IDTOA_BUF];
2652 idtoa(&peer, buf, sizeof(buf));
2653 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2658 /* apparently, r is an improvement on c -- replace */
2660 log("switched from \"%s\" to \"%s\"", c->name, r->name);
2661 if (r->kind == CK_TEMPLATE)
2663 /* instantiate it, filling in peer's ID */
2664 r = rw_instantiate(r, &c->that.host_addr,
2665 #ifdef NAT_TRAVERSAL
2674 st->st_connection = r; /* kill reference to c */
2675 set_cur_connection(r);
2676 connection_discard(c);
2682 /* Decode the variable part of an ID packet (during Quick Mode).
2683 * This is designed for packets that identify clients, not peers.
2684 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2685 * (1) it is wrong and (2) we use this value for inband signalling.
2688 decode_net_id(struct isakmp_ipsec_id *id
2691 , const char *which)
2693 const struct af_info *afi = NULL;
2695 /* Note: the following may be a pointer into static memory
2696 * that may be recycled, but only if the type is not known.
2697 * That case is disposed of very early -- in the first switch.
2699 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2701 switch (id->isaiid_idtype)
2705 /* 818043 NAT-T/L2TP/IPsec for Windows 2000 and XP
2706 * sends an ID_FQDN in the quick mode exchange (name
2709 * This leaves net uninitialised and quick mode will
2710 * fail with "no connection is known"
2712 memset(net, 0, sizeof(ip_subnet));
2716 case ID_IPV4_ADDR_SUBNET:
2717 case ID_IPV4_ADDR_RANGE:
2718 afi = &af_inet4_info;
2721 case ID_IPV6_ADDR_SUBNET:
2722 case ID_IPV6_ADDR_RANGE:
2723 afi = &af_inet6_info;
2727 /* XXX support more */
2728 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2733 switch (id->isaiid_idtype)
2738 ip_address temp_address;
2741 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2745 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2746 , which, idtypename, ugh);
2749 happy(initsubnet(&temp_address, afi->mask_cnt, '0', net));
2750 DBG(DBG_PARSING | DBG_CONTROL,
2752 char temp_buff[SUBNETTOT_BUF];
2754 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2755 DBG_log("%s is %s", which, temp_buff);
2760 case ID_IPV4_ADDR_SUBNET:
2761 case ID_IPV6_ADDR_SUBNET:
2763 ip_address temp_address, temp_mask;
2766 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2768 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2769 , which, idtypename);
2772 ugh = initaddr(id_pbs->cur
2773 , afi->ia_sz, afi->af, &temp_address);
2775 ugh = initaddr(id_pbs->cur + afi->ia_sz
2776 , afi->ia_sz, afi->af, &temp_mask);
2778 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2782 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2783 , which, idtypename, ugh);
2786 DBG(DBG_PARSING | DBG_CONTROL,
2788 char temp_buff[SUBNETTOT_BUF];
2790 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2791 DBG_log("%s is subnet %s", which, temp_buff);
2796 case ID_IPV4_ADDR_RANGE:
2797 case ID_IPV6_ADDR_RANGE:
2799 ip_address temp_address_from, temp_address_to;
2802 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2804 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2805 , which, idtypename);
2808 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2810 ugh = initaddr(id_pbs->cur + afi->ia_sz
2811 , afi->ia_sz, afi->af, &temp_address_to);
2814 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2815 , which, idtypename, ugh);
2819 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2822 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2824 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2825 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2826 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2827 " %s - %s unacceptable: %s"
2828 , which, idtypename, temp_buff1, temp_buff2, ugh);
2831 DBG(DBG_PARSING | DBG_CONTROL,
2833 char temp_buff[SUBNETTOT_BUF];
2835 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2836 DBG_log("%s is subnet %s (received as range)"
2837 , which, temp_buff);
2846 /* like decode, but checks that what is received matches what was sent */
2849 check_net_id(struct isakmp_ipsec_id *id
2854 , const char *which)
2858 if (!decode_net_id(id, id_pbs, &net_temp, which))
2861 if (!samesubnet(net, &net_temp)
2862 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2864 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2871 * look for the existence of a non-expiring preloaded public key
2874 has_preloaded_public_key(struct state *st)
2876 struct connection *c = st->st_connection;
2878 /* do not consider rw connections since
2879 * the peer's identity must be known
2881 if (c->kind == CK_PERMANENT)
2883 struct pubkeyrec *p;
2885 /* look for a matching RSA public key */
2886 for (p = pubkeys; p != NULL; p = p->next)
2888 if (p->alg == PUBKEY_ALG_RSA &&
2889 same_id(&c->that.id, &p->id) &&
2890 p->until == UNDEFINED_TIME)
2892 /* found a preloaded public key */
2901 * Produce the new key material of Quick Mode.
2902 * draft-ietf-ipsec-isakmp-oakley-06.txt section 5.5
2903 * specifies how this is to be done.
2906 compute_proto_keymat(struct state *st
2908 , struct ipsec_proto_info *pi)
2910 size_t needed_len; /* bytes of keying material needed */
2912 /* Add up the requirements for keying material
2913 * (It probably doesn't matter if we produce too much!)
2917 case PROTO_IPSEC_ESP:
2918 switch (pi->attrs.transid)
2924 needed_len = DES_CBC_BLOCK_SIZE;
2927 needed_len = DES_CBC_BLOCK_SIZE * 3;
2930 #ifndef NO_KERNEL_ALG
2931 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2932 /* XXX: check key_len "coupling with kernel.c's */
2933 if (pi->attrs.key_len) {
2934 needed_len=pi->attrs.key_len/8;
2935 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2936 "key_len=%d from peer",
2942 exit_log("transform %s not implemented yet",
2943 enum_show(&esp_transformid_names, pi->attrs.transid));
2945 #ifndef NO_KERNEL_ALG
2946 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2947 "needed_len (after ESP enc)=%d",
2949 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2950 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2953 switch (pi->attrs.auth)
2955 case AUTH_ALGORITHM_NONE:
2957 case AUTH_ALGORITHM_HMAC_MD5:
2958 needed_len += HMAC_MD5_KEY_LEN;
2960 case AUTH_ALGORITHM_HMAC_SHA1:
2961 needed_len += HMAC_SHA1_KEY_LEN;
2963 case AUTH_ALGORITHM_DES_MAC:
2965 exit_log("AUTH algorithm %s not implemented yet",
2966 enum_show(&auth_alg_names, pi->attrs.auth));
2968 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2969 "needed_len (after ESP auth)=%d",
2973 case PROTO_IPSEC_AH:
2974 switch (pi->attrs.transid)
2977 needed_len = HMAC_MD5_KEY_LEN;
2980 needed_len = HMAC_SHA1_KEY_LEN;
2983 exit_log("transform %s not implemented yet",
2984 enum_show(&ah_transformid_names, pi->attrs.transid));
2989 exit_log("protocol %s not implemented yet",
2990 enum_show(&protocol_names, protoid));
2994 pi->keymat_len = needed_len;
2995 /* Allocate space for the keying material.
2996 * Although only needed_len bytes are desired, we
2997 * must round up to a multiple of ctx.hmac_digest_size
2998 * so that our buffer isn't overrun.
3001 struct hmac_ctx ctx_me, ctx_peer;
3002 size_t needed_space; /* space needed for keying material (rounded up) */
3005 hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
3006 ctx_peer = ctx_me; /* duplicate initial conditions */
3008 needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
3009 replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
3010 replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
3014 if (st->st_shared.ptr != NULL)
3016 /* PFS: include the g^xy */
3017 hmac_update_chunk(&ctx_me, st->st_shared);
3018 hmac_update_chunk(&ctx_peer, st->st_shared);
3020 hmac_update(&ctx_me, &protoid, sizeof(protoid));
3021 hmac_update(&ctx_peer, &protoid, sizeof(protoid));
3023 hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
3024 hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
3026 hmac_update_chunk(&ctx_me, st->st_ni);
3027 hmac_update_chunk(&ctx_peer, st->st_ni);
3029 hmac_update_chunk(&ctx_me, st->st_nr);
3030 hmac_update_chunk(&ctx_peer, st->st_nr);
3032 hmac_final(pi->our_keymat + i, &ctx_me);
3033 hmac_final(pi->peer_keymat + i, &ctx_peer);
3035 i += ctx_me.hmac_digest_size;
3036 if (i >= needed_space)
3039 /* more keying material needed: prepare to go around again */
3041 hmac_reinit(&ctx_me);
3042 hmac_reinit(&ctx_peer);
3044 hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size,
3045 ctx_me.hmac_digest_size);
3046 hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size,
3047 ctx_peer.hmac_digest_size);
3052 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
3053 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
3057 compute_keymats(struct state *st)
3059 if (st->st_ah.present)
3060 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
3061 if (st->st_esp.present)
3062 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
3065 /* State Transition Functions.
3067 * The definition of state_microcode_table in demux.c is a good
3068 * overview of these routines.
3070 * - Called from process_packet; result handled by complete_state_transition
3071 * - struct state_microcode member "processor" points to these
3072 * - these routine definitionss are in state order
3073 * - these routines must be restartable from any point of error return:
3074 * beware of memory allocated before any error.
3075 * - output HDR is usually emitted by process_packet (if state_microcode
3076 * member first_out_payload isn't ISAKMP_NEXT_NONE).
3078 * The transition functions' functions include:
3079 * - process and judge payloads
3080 * - update st_iv (result of decryption is in st_new_iv)
3081 * - build reply packet
3084 /* Handle a Main Mode Oakley first packet (responder side).
3088 main_inI1_outR1(struct msg_digest *md)
3090 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
3092 struct connection *c = find_host_connection_mode(&md->iface->addr, pluto_port
3093 , &md->sender, md->sender_port, TRUE);
3097 DBG(DBG_CONTROL, DBG_log("main_inI1_outR1, destination: %s,"
3098 "portof(md->iface->addr): %d," "pluto_port: %d, "
3099 "sender: %s," " md->sender_port: %d,",
3100 inet_ntoa(md->iface->addr.u.v4.sin_addr), ntohs(portof(&md->iface->addr)),
3101 pluto_port, inet_ntoa(md->sender.u.v4.sin_addr), md->sender_port));
3105 /* see if a wildcarded connection can be found */
3106 c = find_host_connection_mode(&md->iface->addr, pluto_port
3107 , (ip_address*)NULL, md->sender_port, TRUE);
3111 /* Create a temporary connection that is a copy of this one.
3112 * His ID isn't declared yet.
3114 c = rw_instantiate(c, &md->sender,
3115 #ifdef NAT_TRAVERSAL
3125 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3126 " but no connection has been authorized"
3127 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr)));
3128 /* XXX notification is in order! */
3134 md->st = st = new_state();
3135 st->st_connection = c;
3136 set_cur_state(st); /* (caller will reset cur_state) */
3137 st->st_try = 0; /* not our job to try again from start */
3138 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3140 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3141 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3143 if (c->dnshostname != NULL)
3145 ip_address new_addr;
3147 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
3148 && !sameaddr(&new_addr, &c->that.host_addr))
3150 c->that.host_addr = new_addr;
3152 load_preshared_secrets();
3156 insert_state(st); /* needs cookies, connection, and msgid (0) */
3158 st->st_doi = ISAKMP_DOI_IPSEC;
3159 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3161 if ((c->kind == CK_INSTANCE) && (c->that.host_port != pluto_port))
3163 log("responding to Main Mode from unknown peer %s:%u"
3164 , ip_str(&c->that.host_addr), c->that.host_port);
3166 else if (c->kind == CK_INSTANCE)
3168 log("responding to Main Mode from unknown peer %s"
3169 , ip_str(&c->that.host_addr));
3173 log("responding to Main Mode");
3176 /* parse_isakmp_sa also spits out a winning SA into our reply,
3177 * so we have to build our md->reply and emit HDR before calling it.
3181 * We can't leave this to comm_handle() because we must
3182 * fill in the cookie.
3185 struct isakmp_hdr r_hdr = md->hdr;
3187 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3188 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3189 r_hdr.isa_np = ISAKMP_NEXT_SA;
3190 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3191 return STF_INTERNAL_ERROR;
3193 DBG(DBG_CONTROL, DBG_log("main_inI1_outR1 -4"));
3194 /* start of SA out */
3196 struct isakmp_sa r_sa = sa_pd->payload.sa;
3198 /* if we use an ID_KEY_ID as own ID, we assume a
3199 * PGPcert peer and have to send the Vendor ID
3200 * ++++ not sure, if this is an interop problem ++++++
3203 if (c->this.id.kind == ID_KEY_ID)
3204 r_sa.isasa_np = ISAKMP_NEXT_VID;
3206 r_sa.isasa_np = ISAKMP_NEXT_NONE;
3209 r_sa.isasa_np = ISAKMP_NEXT_VID;
3210 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3211 return STF_INTERNAL_ERROR;
3213 /* SA body in and out */
3214 RETURN_STF_FAILURE(parse_isakmp_sa_body(&sa_pd->pbs, &sa_pd->payload.sa, &r_sa_pbs
3217 if (c->this.id.kind == ID_KEY_ID)
3219 if (!out_generic_raw(ISAKMP_NEXT_VID, &isakmp_vendor_id_desc, &md->rbody
3220 , pgp_vid, sizeof(pgp_vid)-1, "V_ID"))
3221 return STF_INTERNAL_ERROR;
3224 #ifdef NAT_TRAVERSAL
3225 if (md->nat_traversal_vid && nat_traversal_enabled) {
3226 /* reply if NAT-Traversal draft is supported */
3227 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3228 if ((st->nat_traversal) && (!out_vendorid(ISAKMP_NEXT_NONE,
3229 &md->rbody, md->nat_traversal_vid))) {
3230 return STF_INTERNAL_ERROR;
3236 if (!out_vendorid(ISAKMP_NEXT_NONE, &md->rbody, VID_MISC_DPD))
3237 return STF_INTERNAL_ERROR;
3239 close_message(&md->rbody);
3241 /* save initiator SA for HASH */
3242 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3247 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3248 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3250 * The following are not yet implemented:
3251 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3252 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3253 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3255 * We must verify that the proposal received matches one we sent.
3258 main_inR1_outI2(struct msg_digest *md)
3260 struct state *const st = md->st;
3262 /* verify echoed SA */
3264 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3265 RETURN_STF_FAILURE(parse_isakmp_sa_body(&sapd->pbs
3266 , &sapd->payload.sa, NULL, TRUE, st));
3269 #ifdef NAT_TRAVERSAL
3270 if (nat_traversal_enabled && md->nat_traversal_vid) {
3271 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3275 /**************** build output packet HDR;KE;Ni ****************/
3278 * We can't leave this to comm_handle() because the isa_np
3279 * depends on the type of Auth (eventually).
3281 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3284 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3285 , &md->rbody, ISAKMP_NEXT_NONCE))
3286 return STF_INTERNAL_ERROR;
3288 #ifdef IMPAIR_MTU_BUST_MI2 /* ship a really big VID payload in MI2 message */
3290 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, ISAKMP_NEXT_VID, "Ni"))
3291 return STF_INTERNAL_ERROR;
3293 /* generate a pointless large VID payload to push message over MTU */
3297 if (!out_generic(ISAKMP_NEXT_NONE, &isakmp_vendor_id_desc, &md->rbody
3299 return STF_INTERNAL_ERROR;
3300 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3301 return STF_INTERNAL_ERROR;
3302 close_output_pbs(&vid_pbs);
3306 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, ISAKMP_NEXT_NONE, "Ni"))
3307 return STF_INTERNAL_ERROR;
3310 #ifdef NAT_TRAVERSAL
3311 if (st->nat_traversal & NAT_T_WITH_NATD) {
3312 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3313 return STF_INTERNAL_ERROR;
3317 /* finish message */
3318 close_message(&md->rbody);
3320 /* Reinsert the state, using the responder cookie we just received */
3322 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3323 insert_state(st); /* needs cookies, connection, and msgid (0) */
3329 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3331 * The following are not yet implemented:
3332 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3333 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3335 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3336 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3339 main_inI2_outR2(struct msg_digest *md)
3341 struct state *const st = md->st;
3342 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3344 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3345 bool send_cr = !no_cr_send && (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3346 !has_preloaded_public_key(st);
3349 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3352 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3354 #ifdef NAT_TRAVERSAL
3355 if (st->nat_traversal & NAT_T_WITH_NATD) {
3356 nat_traversal_natd_lookup(md);
3358 if (st->nat_traversal) {
3359 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3361 if (st->nat_traversal & NAT_T_WITH_KA) {
3362 nat_traversal_new_ka_event();
3366 /**************** build output packet HDR;KE;Nr ****************/
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;
3375 #ifdef IMPAIR_MTU_BUST_MR2 /* ship a really big VID payload in MR2 message */
3377 if (!build_and_ship_nonce(&st->st_nr, &md->rbody, ISAKMP_NEXT_VID, "Nr"))
3378 return STF_INTERNAL_ERROR;
3380 /* generate a pointless large VID payload to push message over MTU */
3384 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_NONE,
3385 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3386 return STF_INTERNAL_ERROR;
3387 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3388 return STF_INTERNAL_ERROR;
3389 close_output_pbs(&vid_pbs);
3393 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3394 (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_NONE, "Nr"))
3395 return STF_INTERNAL_ERROR;
3403 struct isakmp_cr cr_hd;
3404 cr_hd.isacr_np = ISAKMP_NEXT_NONE;
3405 cr_hd.isacr_type = CERT_X509_SIGNATURE;
3407 if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, &md->rbody, &cr_pbs))
3408 return STF_INTERNAL_ERROR;
3409 close_output_pbs(&cr_pbs);
3412 #ifdef NAT_TRAVERSAL
3413 if (st->nat_traversal & NAT_T_WITH_NATD) {
3414 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3415 return STF_INTERNAL_ERROR;
3419 /* finish message */
3420 close_message(&md->rbody);
3422 /* next message will be encrypted, but not this one.
3423 * We could defer this calculation.
3425 #ifndef DODGE_DH_MISSING_ZERO_BUG
3426 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3428 if (!generate_skeyids_iv(st))
3429 return STF_FAIL + AUTHENTICATION_FAILED;
3436 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3437 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3439 * The following are not yet implemented.
3440 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3442 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3446 main_inR2_outI3(struct msg_digest *md)
3448 struct state *const st = md->st;
3449 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3450 int auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3451 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3452 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3455 /* send certificate if we have one and auth is RSA */
3456 bool send_cert = (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3457 get_mycert(&mycert, st->st_connection->this.cert);
3459 /* send certificate request, if we don't have a preloaded RSA public key */
3460 bool send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3463 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3466 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3468 /* done parsing; initialize crypto */
3470 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3471 #ifdef DODGE_DH_MISSING_ZERO_BUG
3472 if (st->st_shared.ptr[0] == 0)
3473 return STF_REPLACE_DOOMED_EXCHANGE;
3475 if (!generate_skeyids_iv(st))
3476 return STF_FAIL + AUTHENTICATION_FAILED;
3478 #ifdef NAT_TRAVERSAL
3479 if (st->nat_traversal & NAT_T_WITH_NATD) {
3480 nat_traversal_natd_lookup(md);
3482 if (st->nat_traversal) {
3483 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3485 if (st->nat_traversal & NAT_T_WITH_KA) {
3486 nat_traversal_new_ka_event();
3490 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3491 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3497 struct isakmp_ipsec_id id_hd;
3500 build_id_payload(&id_hd, &id_b, &st->st_connection->this);
3501 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3502 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3503 || !out_chunk(id_b, &id_pbs, "my identity"))
3504 return STF_INTERNAL_ERROR;
3505 close_output_pbs(&id_pbs);
3513 struct isakmp_cert cert_hd;
3514 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3515 cert_hd.isacert_type = mycert.type;
3517 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3518 return STF_INTERNAL_ERROR;
3519 if (!out_chunk(mycert.cert, &cert_pbs, "CERT"))
3520 return STF_INTERNAL_ERROR;
3521 close_output_pbs(&cert_pbs);
3529 struct isakmp_cr cr_hd;
3530 cr_hd.isacr_np = ISAKMP_NEXT_SIG;
3531 cr_hd.isacr_type = mycert.type;
3533 if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, &md->rbody, &cr_pbs))
3534 return STF_INTERNAL_ERROR;
3535 close_output_pbs(&cr_pbs);
3538 /* HASH_I or SIG_I out */
3540 u_char hash_val[MAX_DIGEST_LEN];
3541 size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3543 if (auth_payload == ISAKMP_NEXT_HASH)
3546 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3547 , hash_val, hash_len, "HASH_I"))
3548 return STF_INTERNAL_ERROR;
3553 u_char sig_val[RSA_MAX_OCTETS];
3554 size_t sig_len = RSA_sign_hash(st->st_connection
3555 , sig_val, hash_val, hash_len);
3559 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3560 return STF_FAIL + AUTHENTICATION_FAILED;
3563 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3564 , &md->rbody, sig_val, sig_len, "SIG_I"))
3565 return STF_INTERNAL_ERROR;
3569 /* encrypt message, except for fixed part of header */
3571 /* st_new_iv was computed by generate_skeyids_iv */
3572 if (!encrypt_message(&md->rbody, st))
3573 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3578 /* Shared logic for asynchronous lookup of DNS KEY records.
3579 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3582 struct key_continuation {
3583 struct adns_continuation ac; /* common prefix */
3584 struct msg_digest *md;
3588 report_key_dns_failure(struct id *id, err_t ugh)
3590 char id_buf[IDTOA_BUF]; /* arbitrary limit on length of ID reported */
3592 (void) idtoa(id, id_buf, sizeof(id_buf));
3593 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3594 "; DNS search for KEY failed (%s)", id_buf, ugh);
3597 /* Processs the Main Mode ID Payload and the Authenticator
3598 * (Hash or Signature Payload).
3599 * If a KEY lookup is needed, it is initiated and STF_SUSPEND is returned.
3602 main_id_and_auth(struct msg_digest *md
3603 , bool initiator /* are we the Initiator? */
3605 , cont_fn_t cont_fn) /* continuation function */
3607 struct state *st = md->st;
3608 u_char hash_val[MAX_DIGEST_LEN];
3610 stf_status r = STF_OK;
3613 * Note: this may switch the connection being used!
3615 if (!aggrmode && !decode_peer_id(md, initiator, FALSE))
3616 return STF_FAIL + INVALID_ID_INFORMATION;
3618 /* Hash the ID Payload.
3619 * main_mode_hash requires idpl->cur to be at end of payload
3620 * so we temporarily set if so.
3623 hash_len = aggr_mode_hash(st, hash_val, !initiator, FALSE);
3626 pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3627 u_int8_t *old_cur = idpl->cur;
3629 idpl->cur = idpl->roof;
3630 hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3631 idpl->cur = old_cur;
3634 switch (st->st_oakley.auth)
3636 case OAKLEY_PRESHARED_KEY:
3638 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3640 if (pbs_left(hash_pbs) != hash_len
3641 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3643 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3644 , hash_pbs->cur, pbs_left(hash_pbs));
3645 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3646 r = STF_FAIL + INVALID_HASH_INFORMATION;
3651 case OAKLEY_RSA_SIG:
3652 r = RSA_check_signature(st, hash_val, hash_len
3653 , &md->chain[ISAKMP_NEXT_SIG]->pbs);
3655 if (r == STF_SUSPEND)
3657 /* initiate asynchronous DNS lookup for KEY record(s) */
3658 struct key_continuation *kc
3659 = alloc_thing(struct key_continuation, "key continuation");
3662 /* Record that state is used by a suspended md */
3663 passert(st->st_suspended_md == NULL);
3664 kc->md = st->st_suspended_md = md;
3666 ugh = start_adns_query(&st->st_connection->that.id
3667 , NULL /* no sgw for KEY */
3674 report_key_dns_failure(&st->st_connection->that.id, ugh);
3675 st->st_suspended_md = NULL;
3676 r = STF_FAIL + INVALID_KEY_INFORMATION;
3685 DBG(DBG_CRYPT, DBG_log("authentication succeeded"));
3691 key_continue(struct adns_continuation *cr, err_t ugh
3692 , stf_status (*tail)(struct msg_digest *md))
3695 struct key_continuation *kc = (void *)cr;
3696 struct state *st = kc->md->st;
3698 passert(cur_state == NULL);
3699 /* if st == NULL, our state has been deleted -- just clean up */
3702 passert(st->st_suspended_md == kc->md);
3703 st->st_suspended_md = NULL; /* no longer connected or suspended */
3704 cur_state = kc->md->st;
3707 report_key_dns_failure(&st->st_connection->that.id, ugh);
3708 r = STF_FAIL + INVALID_KEY_INFORMATION;
3712 passert(keys_from_dns != NULL);
3713 r = (*tail)(kc->md);
3714 passert(keys_from_dns == NULL);
3716 complete_state_transition(&kc->md, r);
3723 * PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
3724 * DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
3725 * PKE_AUTH, RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
3727 * Broken into parts to allow asynchronous DNS for KEY records.
3729 * - main_inI3_outR3 to start
3730 * - main_inI3_outR3_tail to finish or suspend for DNS lookup
3731 * - main_inI3_outR3_continue to start main_inI3_outR3_tail again
3733 static stf_status main_inI3_outR3_tail(struct msg_digest *md); /* forward */
3736 main_inI3_outR3(struct msg_digest *md)
3738 passert(keys_from_dns == NULL);
3739 return main_inI3_outR3_tail(md);
3743 main_inI3_outR3_continue(struct adns_continuation *cr, err_t ugh)
3745 key_continue(cr, ugh, main_inI3_outR3_tail);
3749 main_inI3_outR3_tail(struct msg_digest *md)
3751 struct state *const st = md->st;
3753 u_int8_t auth_payload;
3754 pb_stream r_id_pbs; /* ID Payload; also used for hash calculation */
3758 /* HASH_I or SIG_I in */
3760 stf_status r = main_id_and_auth(md, FALSE, FALSE
3761 , main_inI3_outR3_continue);
3767 /* send certificate if we have one and auth is RSA */
3768 send_cert = (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3769 get_mycert(&mycert, st->st_connection->this.cert);
3771 /*************** build output packet HDR*;IDir;HASH/SIG_R ***************/
3772 /* proccess_packet() would automatically generate the HDR*
3773 * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
3774 * We don't do this because we wish there to be no partially
3775 * built output packet if we need to suspend for asynch DNS.
3777 /* ??? NOTE: this is almost the same as main_inR2_outI3's code */
3780 * If auth were PKE_AUTH or RPKE_AUTH, ISAKMP_NEXT_HASH would
3783 echo_hdr(md, TRUE, ISAKMP_NEXT_ID);
3785 auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3786 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3790 struct isakmp_ipsec_id id_hd;
3793 build_id_payload(&id_hd, &id_b, &st->st_connection->this);
3794 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3795 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &r_id_pbs)
3796 || !out_chunk(id_b, &r_id_pbs, "my identity"))
3797 return STF_INTERNAL_ERROR;
3799 close_output_pbs(&r_id_pbs);
3802 /* CERT out, if we have one */
3807 struct isakmp_cert cert_hd;
3808 cert_hd.isacert_np = ISAKMP_NEXT_SIG;
3809 cert_hd.isacert_type = mycert.type;
3811 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3812 return STF_INTERNAL_ERROR;
3813 if (!out_chunk(mycert.cert, &cert_pbs, "CERT"))
3814 return STF_INTERNAL_ERROR;
3815 close_output_pbs(&cert_pbs);
3818 /* HASH_R or SIG_R out */
3820 u_char hash_val[MAX_DIGEST_LEN];
3821 size_t hash_len = main_mode_hash(st, hash_val, FALSE, &r_id_pbs);
3823 if (auth_payload == ISAKMP_NEXT_HASH)
3826 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3827 , hash_val, hash_len, "HASH_R"))
3828 return STF_INTERNAL_ERROR;
3833 u_char sig_val[RSA_MAX_OCTETS];
3834 size_t sig_len = RSA_sign_hash(st->st_connection
3835 , sig_val, hash_val, hash_len);
3839 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3840 return STF_FAIL + AUTHENTICATION_FAILED;
3843 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3844 , &md->rbody, sig_val, sig_len, "SIG_R"))
3845 return STF_INTERNAL_ERROR;
3849 /* encrypt message, sans fixed part of header */
3851 DBG(DBG_CONTROL, DBG_log(" main_inI3_outR3 -4"));
3852 if (!encrypt_message(&md->rbody, st))
3853 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3855 /* Last block of Phase 1 (R3), kept for Phase 2 IV generation */
3856 DBG_cond_dump(DBG_CRYPT, "last encrypted block of Phase 1:"
3857 , st->st_new_iv, st->st_new_iv_len);
3859 ISAKMP_SA_established(st->st_connection, st->st_serialno);
3861 DBG(DBG_CONTROL, DBG_log(" main_inI3_outR3 -5"));
3862 /* ??? If st->st_connectionc->gw_info != NULL,
3863 * we should keep the public key -- it tested out.
3870 * Handle HDR*;IDir;HASH/SIG_R from responder.
3872 * Broken into parts to allow asynchronous DNS for KEY records.
3874 * - main_inR3 to start
3875 * - main_inR3_tail to finish or suspend for DNS lookup
3876 * - main_inR3_continue to start main_inR3_tail again
3879 static stf_status main_inR3_tail(struct msg_digest *md); /* forward */
3882 main_inR3(struct msg_digest *md)
3884 passert(keys_from_dns == NULL);
3885 return main_inR3_tail(md);
3889 main_inR3_continue(struct adns_continuation *cr, err_t ugh)
3891 key_continue(cr, ugh, main_inR3_tail);
3895 main_inR3_tail(struct msg_digest *md)
3897 struct state *const st = md->st;
3899 /* HASH_R or SIG_R in */
3901 stf_status r = main_id_and_auth(md, TRUE, FALSE, main_inR3_continue);
3907 /**************** done input ****************/
3909 ISAKMP_SA_established(st->st_connection, st->st_serialno);
3911 /* ??? If c->gw_info != NULL,
3912 * we should keep the public key -- it tested out.
3915 update_iv(st); /* finalize our Phase 1 IV */
3920 /* Handle first message of Phase 2 -- Quick Mode.
3921 * HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
3922 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
3923 * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
3924 * Installs inbound IPsec SAs.
3925 * Although this seems early, we know enough to do so, and
3926 * this way we know that it is soon enough to catch all
3927 * packets that other side could send using this IPsec SA.
3929 * Broken into parts to allow asynchronous DNS for TXT records:
3931 * - quick_inI1_outR1 starts the ball rolling.
3932 * It checks and parses enough to learn the Phase 2 IDs
3934 * - quick_inI1_outR1_tail does the rest of the job
3935 * unless DNS must be consulted. In that case,
3936 * it starts a DNS query, salts away what is needed
3937 * to continue, and suspends.
3939 * - quick_inI1_outR1_continue will restart quick_inI1_outR1_tail
3940 * when DNS comes back with an answer.
3942 * A big chunk of quick_inI1_outR1_tail is executed twice.
3943 * This is necessary because the set of connections
3944 * might change while we are awaiting DNS.
3945 * When first called, gateways_from_dns == NULL. If DNS is
3946 * consulted asynchronously, gateways_from_dns != NULL the second time.
3947 * Remember that our state object might disappear too!
3950 /* hold anything we can handle of a Phase 2 ID */
3957 struct verify_continuation {
3958 struct adns_continuation ac; /* common prefix */
3959 struct msg_digest *md;
3960 struct p2id my, his;
3961 unsigned int new_iv_len; /* p1st's might change */
3962 u_char new_iv[MAX_DIGEST_LEN];
3963 /* int whackfd; */ /* not needed */
3966 static stf_status quick_inI1_outR1_tail(struct msg_digest *md
3967 , struct p2id *my, struct p2id *his
3968 , unsigned int new_iv_len
3969 , const u_char new_iv[MAX_DIGEST_LEN]); /* forward */
3972 /* STATE_AGGR_R0: HDR, SA, KE, Ni, IDii
3973 * --> HDR, SA, KE, Nr, IDir, HASH_R/SIG_R
3976 aggr_inI1_outR1(struct msg_digest *md)
3978 /* With Aggressive Mode, we get an ID payload in this, the first
3979 * message, so we can use it to index the preshared-secrets
3980 * when the IP address would not be meaningful (i.e. Road
3981 * Warrior). So our first task is to unravel the ID payload.
3984 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
3986 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3987 struct connection *c = find_host_connection_mode(&md->iface->addr, pluto_port
3988 , &md->sender, md->sender_port, FALSE);
3992 DBG(DBG_CONTROL, DBG_log("aggr_inI1_outR1,"
3993 //"destination: %s," "portof(md->iface->addr): %d,"
3994 "sender: %s," " md->sender_port: %d,",
3995 //inet_ntoa(md->iface->addr.u.v4.sin_addr), ntohs(portof(&md->iface->addr)),
3996 inet_ntoa(md->sender.u.v4.sin_addr), md->sender_port));
4000 /* see if a wildcarded connection can be found */
4001 c = find_host_connection_mode(&md->iface->addr, pluto_port
4002 , (const ip_address *)NULL, md->sender_port, FALSE);
4005 /* create a temporary connection that is a copy of this one */
4006 c = rw_instantiate(c, &md->sender,
4007 #ifdef NAT_TRAVERSAL
4017 loglog(RC_LOG_SERIOUS, "initial Aggressive Mode message from %s"
4018 " but no (wildcard) connection has been configured"
4019 , inet_ntoa(md->sender.u.v4.sin_addr));
4020 /* XXX notification is in order! */
4026 md->st = st = new_state();
4027 st->st_connection = c;
4028 set_cur_state(st); /* (caller will reset cur_state) */
4030 st->st_policy |= POLICY_AGGRESSIVE;
4032 /* KLUDGE: st_oakley determined by SA parse which wants the pre-
4033 shared secret already determinable by decode_peer_id! */
4034 /* we really need to peek into the SA to see if it is RSASIG
4035 or something else. */
4036 st->st_oakley.auth = OAKLEY_PRESHARED_KEY; /* FIXME! */
4038 if (!decode_peer_id(md, FALSE, TRUE))
4042 DBG(DBG_CONTROL, DBG_log("aggr_inI1_outR1 5, md->iface->addr.u.v4: %x,"
4045 " md->sender_port: %x,", md->iface->addr.u.v4, pluto_port,
4046 md->sender.u.v4.sin_addr.s_addr, md->sender_port));
4047 (void) idtoa(&st->st_connection->that.id, buf, sizeof(buf));
4048 loglog(RC_LOG_SERIOUS,
4049 "initial Aggressive Mode packet claiming to be from %s"
4050 " on %s but no connection has been authorized",
4051 buf, inet_ntoa(md->sin.sin_addr));
4052 insert_state(st); /* schedule event to discard connection */
4053 /* XXX notification is in order! */
4054 return STF_FAIL + INVALID_ID_INFORMATION;
4060 st->st_try = 0; /* Not our job to try again from start */
4061 st->st_policy = st->st_connection->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
4064 /* Copy identity from temporary state object */
4065 st->st_peeridentity = tempstate.st_peeridentity;
4066 st->st_peeridentity_type = tempstate.st_peeridentity_type;
4067 st->st_peeruserprotoid = tempstate.st_peeruserprotoid;
4068 st->st_peeruserport = tempstate.st_peeruserport;
4071 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
4072 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
4074 if (c->dnshostname != NULL)
4076 ip_address new_addr;
4078 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
4079 && !sameaddr(&new_addr, &c->that.host_addr))
4081 c->that.host_addr = new_addr;
4083 load_preshared_secrets();
4087 insert_state(st); /* needs cookies, connection, and msgid (0) */
4089 st->st_doi = ISAKMP_DOI_IPSEC;
4090 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
4091 st->st_state = STATE_AGGR_R1;
4093 log("responding to Aggressive Mode, state #%lu, connection \"%s\""
4095 , st->st_serialno, st->st_connection->name
4096 , (st->st_connection->kind == CK_INSTANCE) ? "(Road Warrior)" : ""
4097 , inet_ntoa(st->st_connection->that.host_addr.u.v4.sin_addr));
4099 /* save initiator SA for HASH */
4100 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs),
4101 "sa in aggr_inI1_outR1()");
4103 /* parse_isakmp_sa also spits out a winning SA into our reply,
4104 * so we have to build our md->reply and emit HDR before calling it.
4110 struct isakmp_hdr r_hdr = md->hdr;
4112 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
4113 r_hdr.isa_np = ISAKMP_NEXT_SA;
4114 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
4115 impossible(); /* surely must have room and be well-formed */
4118 /* start of SA out */
4120 struct isakmp_sa r_sa = sa_pd->payload.sa;
4123 r_sa.isasa_np = ISAKMP_NEXT_VID;
4124 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
4125 return STF_INTERNAL_ERROR;
4127 /* SA body in and out */
4128 r = parse_isakmp_sa_body(&sa_pd->pbs, &sa_pd->payload.sa,
4129 &r_sa_pbs, FALSE, st);
4130 if (r != NOTHING_WRONG)
4131 return STF_FAIL + r;
4134 /* don't know until after SA body has been parsed */
4135 auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
4136 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
4140 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
4143 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
4146 /************** build rest of output: KE, Nr, IDir, HASH_R/SIG_R ********/
4148 #ifdef NAT_TRAVERSAL
4149 if (md->nat_traversal_vid && nat_traversal_enabled) {
4150 /* reply if NAT-Traversal draft is supported */
4151 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
4152 if ((st->nat_traversal) && (!out_vendorid(ISAKMP_NEXT_NONE,
4153 &md->rbody, md->nat_traversal_vid))) {
4154 return STF_INTERNAL_ERROR;
4160 if (!out_vendorid(ISAKMP_NEXT_KE, &md->rbody, VID_MISC_DPD))
4161 return STF_INTERNAL_ERROR;
4164 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group,
4165 &md->rbody, ISAKMP_NEXT_NONCE))
4166 return STF_INTERNAL_ERROR;
4169 if (!build_and_ship_nonce(&st->st_nr, &md->rbody, ISAKMP_NEXT_ID, "Nr"))
4170 return STF_INTERNAL_ERROR;
4174 struct isakmp_ipsec_id id_hd;
4178 build_id_payload(&id_hd, &id_b, &st->st_connection->this);
4179 id_hd.isaiid_np = auth_payload;
4180 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &r_id_pbs)
4181 || !out_chunk(id_b, &r_id_pbs, "my identity"))
4182 return STF_INTERNAL_ERROR;
4183 close_output_pbs(&r_id_pbs);
4187 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
4188 #ifdef DODGE_DH_MISSING_ZERO_BUG
4189 if (st->st_shared.ptr[0] == 0)
4190 return STF_DROP_DOOMED_EXCHANGE;
4193 if (!generate_skeyids_iv(st))
4194 return STF_FAIL + AUTHENTICATION_FAILED;
4197 /* HASH_R or SIG_R out */
4199 u_char hash_val[MAX_DIGEST_LEN];
4200 size_t hash_len = aggr_mode_hash(st, hash_val, FALSE, TRUE);
4202 if (auth_payload == ISAKMP_NEXT_HASH)
4205 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
4206 , hash_val, hash_len, "HASH_R"))
4207 return STF_INTERNAL_ERROR;
4212 u_char sig_val[RSA_MAX_OCTETS];
4213 size_t sig_len = RSA_sign_hash(st->st_connection
4214 , sig_val, hash_val, hash_len);
4218 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
4219 return STF_FAIL + AUTHENTICATION_FAILED;
4222 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
4223 , &md->rbody, sig_val, sig_len, "SIG_R"))
4224 return STF_INTERNAL_ERROR;
4228 #ifdef NAT_TRAVERSAL
4229 if (st->nat_traversal & NAT_T_WITH_NATD) {
4230 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
4231 return STF_INTERNAL_ERROR;
4235 /* finish message */
4236 close_message(&md->rbody);
4242 * Broken into parts to allow asynchronous DNS for KEY records.
4244 * - aggr_inI3_outR3 to start
4245 * - aggr_inI3_outR3_tail to finish or suspend for DNS lookup
4246 * - aggr_inI3_outR3_continue to start main_inI3_outR3_tail again
4248 static stf_status aggr_inR1_outI2_tail(struct msg_digest *md); /* forward */
4251 aggr_inR1_outI2(struct msg_digest *md)
4253 passert(keys_from_dns == NULL);
4254 return aggr_inR1_outI2_tail(md);
4258 aggr_inR1_outI2_continue(struct adns_continuation *cr, err_t ugh)
4260 key_continue(cr, ugh, aggr_inR1_outI2_tail);
4264 aggr_inR1_outI2_tail(struct msg_digest *md)
4266 /* With Aggressive Mode, we get an ID payload in this, the second
4267 * message, so we can use it to index the preshared-secrets
4268 * when the IP address would not be meaningful (i.e. Road
4269 * Warrior). So our first task is to unravel the ID payload.
4271 struct state *const st = md->st;
4272 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
4273 struct connection *c = st->st_connection;
4274 u_int8_t auth_payload;
4276 st->st_policy |= POLICY_AGGRESSIVE;
4278 #ifdef NAT_TRAVERSAL
4279 if (md->nat_traversal_vid && nat_traversal_enabled) {
4280 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
4284 if (!decode_peer_id(md, FALSE, TRUE))
4288 (void) idtoa(&st->st_connection->that.id, buf, sizeof(buf));
4289 loglog(RC_LOG_SERIOUS,
4290 "Initial Aggressive Mode packet claiming to be from %s"
4291 " on %s but no connection has been authorized",
4292 buf, inet_ntoa(md->sender.u.v4.sin_addr));
4293 /* XXX notification is in order! */
4294 return STF_FAIL + INVALID_ID_INFORMATION;
4296 auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
4297 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
4299 /* verify echoed SA */
4301 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
4302 notification_t r = \
4303 parse_isakmp_sa_body(&sapd->pbs, &sapd->payload.sa,
4306 if (r != NOTHING_WRONG)
4307 return STF_FAIL + r;
4311 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
4314 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
4316 /* moved the following up as we need Rcookie for hash, skeyids */
4317 /* Reinsert the state, using the responder cookie we just received */
4319 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
4320 insert_state(st); /* needs cookies, connection, and msgid (0) */
4322 /* Generate SKEYID, SKEYID_A, SKEYID_D, SKEYID_E */
4323 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
4324 #ifdef DODGE_DH_MISSING_ZERO_BUG
4325 if (st->st_shared.ptr[0] == 0)
4326 return STF_REPLACE_DOOMED_EXCHANGE;
4328 if (!generate_skeyids_iv(st))
4329 return STF_FAIL + AUTHENTICATION_FAILED;
4332 #ifdef NAT_TRAVERSAL
4333 if (st->nat_traversal & NAT_T_WITH_NATD) {
4334 nat_traversal_natd_lookup(md);
4336 if (st->nat_traversal) {
4337 nat_traversal_show_result(st->nat_traversal, md->sender_port);
4339 if (st->nat_traversal & NAT_T_WITH_KA) {
4340 nat_traversal_new_ka_event();
4344 /* HASH_I or SIG_I in */
4346 stf_status r = main_id_and_auth(md, TRUE, TRUE
4347 , aggr_inR1_outI2_continue);
4353 /*************** build output packet HDR*;IDir;HASH/SIG_R ***************/
4354 /* proccess_packet() would automatically generate the HDR*
4355 * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
4356 * We don't do this because we wish there to be no partially
4357 * built output packet if we need to suspend for asynch DNS.
4359 /* ??? NOTE: this is almost the same as main_inR2_outI3's code */
4362 * If auth were PKE_AUTH or RPKE_AUTH, ISAKMP_NEXT_HASH would
4365 echo_hdr(md, TRUE, auth_payload);
4368 /* HASH_I or SIG_I out */
4370 u_char hash_val[MAX_DIGEST_LEN];
4371 size_t hash_len = aggr_mode_hash(st, hash_val, TRUE, TRUE);
4373 if (auth_payload == ISAKMP_NEXT_HASH)
4376 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
4377 , hash_val, hash_len, "HASH_I"))
4378 return STF_INTERNAL_ERROR;
4383 u_char sig_val[RSA_MAX_OCTETS];
4384 size_t sig_len = RSA_sign_hash(st->st_connection
4385 , sig_val, hash_val, hash_len);
4389 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
4390 return STF_FAIL + AUTHENTICATION_FAILED;
4393 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
4394 , &md->rbody, sig_val, sig_len, "SIG_I"))
4395 return STF_INTERNAL_ERROR;
4398 #ifdef NAT_TRAVERSAL
4399 if (st->nat_traversal & NAT_T_WITH_NATD) {
4400 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
4401 return STF_INTERNAL_ERROR;
4405 /* encrypt message, sans fixed part of header */
4407 /* st_new_iv was computed by generate_skeyids_iv */
4408 if (!encrypt_message(&md->rbody, st))
4409 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
4411 ISAKMP_SA_established(st->st_connection, st->st_serialno);
4418 * HDR*, HASH_I --> done
4420 * Broken into parts to allow asynchronous DNS for KEY records.
4422 * - aggr_inR3 to start
4423 * - aggr_inR3_tail to finish or suspend for DNS lookup
4424 * - aggr_inR3_continue to start aggr_inR3_tail again
4427 static stf_status aggr_inI2_tail(struct msg_digest *md); /* forward */
4430 aggr_inI2(struct msg_digest *md)
4432 passert(keys_from_dns == NULL);
4433 return aggr_inI2_tail(md);
4437 aggr_inI2_continue(struct adns_continuation *cr, err_t ugh)
4439 key_continue(cr, ugh, aggr_inI2_tail);
4443 aggr_inI2_tail(struct msg_digest *md)
4445 struct state *const st = md->st;
4446 struct connection *c = st->st_connection;
4448 #ifdef NAT_TRAVERSAL
4449 if (st->nat_traversal & NAT_T_WITH_NATD) {
4450 nat_traversal_natd_lookup(md);
4452 if (st->nat_traversal) {
4453 nat_traversal_show_result(st->nat_traversal, md->sender_port);
4455 if (st->nat_traversal & NAT_T_WITH_KA) {
4456 nat_traversal_new_ka_event();
4460 /* HASH_R or SIG_R in */
4462 stf_status r = main_id_and_auth(md, FALSE, TRUE, aggr_inI2_continue);
4467 /**************** done input ****************/
4469 ISAKMP_SA_established(st->st_connection, st->st_serialno);
4471 /* ??? If c->gw_info != NULL,
4472 * we should keep the public key -- it tested out.
4474 update_iv(st); /* finalize our Phase 1 IV */
4479 quick_inI1_outR1(struct msg_digest *md)
4481 const struct state *const p1st = md->st;
4482 struct connection *c = p1st->st_connection;
4483 struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
4484 struct p2id my, his;
4488 , quick_mode_hash12(hash_val, hash_pbs->roof, md->message_pbs.roof
4489 , p1st, &md->hdr.isa_msgid, FALSE)
4490 , "HASH(1)", "Quick I1");
4492 /* [ IDci, IDcr ] in
4493 * We do this now (probably out of physical order) because
4494 * we wish to select the correct connection before we consult
4500 /* ??? we are assuming IPSEC_DOI */
4502 /* IDci (initiator is peer) */
4504 if (!decode_net_id(&id_pd->payload.ipsec_id, &id_pd->pbs
4505 , &his.net, "peer client"))
4506 return STF_FAIL + INVALID_ID_INFORMATION;
4508 his.proto = id_pd->payload.ipsec_id.isaiid_protoid;
4509 his.port = id_pd->payload.ipsec_id.isaiid_port;
4511 /* IDcr (we are responder) */
4513 if (!decode_net_id(&id_pd->next->payload.ipsec_id, &id_pd->next->pbs
4514 , &my.net, "our client"))
4515 return STF_FAIL + INVALID_ID_INFORMATION;
4517 my.proto = id_pd->next->payload.ipsec_id.isaiid_protoid;
4518 my.port = id_pd->next->payload.ipsec_id.isaiid_port;
4522 /* implicit IDci and IDcr: peer and self */
4523 if (!sameaddrtype(&c->this.host_addr, &c->that.host_addr))
4526 happy(addrtosubnet(&c->this.host_addr, &my.net));
4527 happy(addrtosubnet(&c->that.host_addr, &his.net));
4528 his.proto = my.proto = 0;
4529 his.port = my.port = 0;
4531 passert(gateways_from_dns == NULL);
4532 return quick_inI1_outR1_tail(md, &my, &his
4533 , p1st->st_new_iv_len, p1st->st_new_iv);
4537 report_verify_failure(struct state *st, struct p2id *his, err_t ugh)
4539 char fgwb[ADDRTOT_BUF]
4541 ip_address peer_client;
4543 addrtot(&st->st_connection->that.host_addr, 0, fgwb, sizeof(fgwb));
4544 networkof(&his->net, &peer_client);
4545 addrtot(&peer_client, 0, cb, sizeof(cb));
4546 loglog(RC_OPPOFAILURE
4547 , "gateway %s claims client %s, but DNS for client fails to confirm: %s"
4552 quick_inI1_outR1_continue(struct adns_continuation *cr, err_t ugh)
4555 struct verify_continuation *vc = (void *)cr;
4556 struct state *st = vc->md->st;
4558 passert(cur_state == NULL);
4559 /* if st == NULL, our state has been deleted -- just clean up */
4562 passert(st->st_suspended_md == vc->md);
4563 st->st_suspended_md = NULL; /* no longer connected or suspended */
4564 cur_state = vc->md->st;
4567 report_verify_failure(st, &vc->his, ugh);
4568 r = STF_FAIL + INVALID_ID_INFORMATION;
4572 passert(gateways_from_dns != NULL);
4573 r = quick_inI1_outR1_tail(vc->md, &vc->my, &vc->his
4574 , vc->new_iv_len, vc->new_iv);
4575 passert(gateways_from_dns == NULL);
4577 complete_state_transition(&vc->md, r);
4584 quick_inI1_outR1_tail(struct msg_digest *md
4585 , struct p2id *my, struct p2id *his
4586 , unsigned int new_iv_len
4587 , const u_char new_iv[MAX_DIGEST_LEN])
4589 struct state *const p1st = md->st;
4590 struct connection *c = p1st->st_connection;
4591 struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
4592 ip_subnet *our_net = &my->net
4593 , *his_net = &his->net;
4595 u_char /* set by START_HASH_PAYLOAD: */
4596 *r_hashval, /* where in reply to jam hash value */
4597 *r_hash_start; /* from where to start hashing */
4599 /* Now that we have identities of client subnets, we must look for
4600 * a suitable connection (our current one only matches for hosts).
4603 struct connection *p = find_client_connection(c
4604 , our_net, his_net, my->proto, my->port, his->proto, his->port);
4608 /* This message occurs in very puzzling circumstances
4609 * so we must add as much information and beauty as we can.
4614 char buf[2*SUBNETTOT_BUF + 2*ADDRTOT_BUF + 2*IDTOA_BUF + 2*ADDRTOT_BUF + 12]; /* + 12 for separating */
4617 me.client = *our_net;
4618 me.has_client = !subnetishost(our_net)
4619 || !addrinsubnet(&me.host_addr, our_net);
4620 me.protocol = my->proto;
4623 he.client = *his_net;
4624 he.has_client = !subnetishost(his_net)
4625 || !addrinsubnet(&he.host_addr, his_net);
4626 he.protocol = his->proto;
4627 he.port = his->port;
4629 l = format_end(buf, sizeof(buf), &me, NULL, TRUE);
4630 l += snprintf(buf + l, sizeof(buf) - l, "...");
4631 (void)format_end(buf + l, sizeof(buf) - l, &he, NULL, FALSE);
4632 log("cannot respond to IPsec SA request"
4633 " because no connection is known for %s"
4635 return STF_FAIL + INVALID_ID_INFORMATION;
4639 /* We've got a better connection: it can support the
4640 * specified clients. But it may need instantiation.
4642 if (p->kind == CK_TEMPLATE)
4644 /* Yup, it needs instantiation. How much?
4645 * Is it a Road Warrior connection (simple)
4646 * or is it an Opportunistic connection (needing gw validation)?
4648 if (p->policy & POLICY_OPPO)
4651 * We need to determine if this peer is authorized
4652 * to negotiate for this client! If the peer's
4653 * client is the peer, we assume that it is authorized.
4654 * Since p isn't yet instantiated, we need to look
4655 * in c for description of peer.
4657 ip_address our_client
4660 passert(subnetishost(our_net) && subnetishost(his_net));
4662 networkof(our_net, &our_client);
4663 networkof(his_net, &his_client);
4665 /* refcounts for gateways_from_dns must balance,
4666 * but NULL needs no count!
4668 if (!sameaddr(&c->that.host_addr, &his_client))
4670 if (gateways_from_dns == NULL)
4672 /* initiate asynch DNS lookup and suspend */
4673 struct verify_continuation *vc
4674 = alloc_thing(struct verify_continuation
4675 , "verify continuation");
4679 /* Record that state is used by a suspended md */
4680 passert(p1st->st_suspended_md == NULL);
4681 vc->md = p1st->st_suspended_md = md;
4685 vc->new_iv_len = p1st->st_new_iv_len;
4686 memcpy(vc->new_iv, p1st->st_new_iv, p1st->st_new_iv_len);
4687 iptoid(&his_client, &pc_id);
4688 ugh = start_adns_query(&pc_id
4691 , quick_inI1_outR1_continue
4695 report_verify_failure(p1st, his, ugh);
4696 p1st->st_suspended_md = NULL;
4697 return STF_FAIL + INVALID_ID_INFORMATION;
4706 /* use result of asynch DNS lookup */
4707 struct gw_info *gwp;
4709 /* check that the public key that authenticated
4710 * the ISAKMP SA (p1st) will do for this gateway.
4712 for (gwp = gateways_from_dns; ; gwp = gwp->next)
4717 loglog(RC_OPPOFAILURE, "peer and client disagree about public key");
4718 gw_delref(&gateways_from_dns);
4719 return STF_FAIL + INVALID_ID_INFORMATION;
4721 passert(same_id(&gwp->gw_id, &c->that.id));
4722 /* If there is a key from the TXT record,
4723 * we count it as a win if we match the key.
4724 * If there was no key, we claim a match since
4725 * it implies fetching a KEY from the same
4726 * place we must have gotten it.
4728 if (!gwp->gw_key_present
4729 || same_RSA_public_key(&p1st->st_peer_pubkey->u.rsa
4736 /* Instantiate inbound Opportunistic connection,
4737 * carrying over authenticated peer ID
4738 * and filling in a few more details.
4740 p = oppo_instantiate(p, &c->that.host_addr, &c->that.id
4741 , gateways_from_dns, &our_client, &his_client);
4742 gw_delref(&gateways_from_dns); /* gateways_from_dns is dead */
4746 /* Plain Road Warrior:
4747 * instantiate, carrying over authenticated peer ID
4749 p = rw_instantiate(p, &c->that.host_addr,
4750 #ifdef NAT_TRAVERSAL
4760 /* temporarily bump up cur_debugging to get "using..." message
4761 * printed if we'd want it with new connection.
4764 unsigned int old_cur_debugging = cur_debugging;
4766 cur_debugging |= p->extra_debugging;
4767 DBG(DBG_CONTROL, DBG_log("using connection \"%s\"", p->name));
4768 cur_debugging = old_cur_debugging;
4773 /* fill in the client's true ip address/subnet */
4774 if (p->that.has_client_wildcard)
4776 p->that.client = *his_net;
4777 p->that.has_client_wildcard = FALSE;
4780 else if (is_virtual_connection(c))
4782 c->that.client = *his_net;
4783 c->that.virt = NULL;
4784 if (subnetishost(his_net) && addrinsubnet(&c->that.host_addr, his_net))
4785 c->that.has_client = FALSE;
4790 /* now that we are sure of our connection, create our new state */
4792 struct state *const st = duplicate_state(p1st);
4794 /* first: fill in missing bits of our new state object
4795 * note: we don't copy over st_peer_pubkey, the public key
4796 * that authenticated the ISAKMP SA. We only need it in this
4797 * routine, so we can "reach back" to p1st to get it.
4800 if (st->st_connection != c)
4802 struct connection *t = st->st_connection;
4804 st->st_connection = c;
4805 set_cur_connection(c);
4806 connection_discard(t);
4809 st->st_try = 0; /* not our job to try again from start */
4811 st->st_msgid = md->hdr.isa_msgid;
4813 st->st_new_iv_len = new_iv_len;
4814 memcpy(st->st_new_iv, new_iv, new_iv_len);
4816 set_cur_state(st); /* (caller will reset) */
4817 md->st = st; /* feed back new state */
4819 st->st_peeruserprotoid = his->proto;
4820 st->st_peeruserport = his->port;
4821 st->st_myuserprotoid = my->proto;
4822 st->st_myuserport = my->port;
4824 if (c->dnshostname != NULL)
4826 ip_address new_addr;
4828 if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
4829 && !sameaddr(&new_addr, &c->that.host_addr))
4831 c->that.host_addr = new_addr;
4833 load_preshared_secrets();
4837 insert_state(st); /* needs cookies, connection, and msgid */
4839 /* copy the connection's
4840 * IPSEC policy into our state. The ISAKMP policy is water under
4841 * the bridge, I think. It will reflect the ISAKMP SA that we
4844 st->st_policy = (p1st->st_policy & POLICY_ISAKMP_MASK)
4845 | (c->policy & ~POLICY_ISAKMP_MASK);
4847 #ifdef NAT_TRAVERSAL
4848 if (p1st->nat_traversal & NAT_T_DETECTED) {
4849 st->nat_traversal = p1st->nat_traversal;
4850 nat_traversal_change_port_lookup(md, md->st);
4853 st->nat_traversal = 0;
4855 if ((st->nat_traversal & NAT_T_DETECTED) &&
4856 (st->nat_traversal & NAT_T_WITH_NATOA)) {
4857 nat_traversal_natoa_lookup(md);
4861 /* Start the output packet.
4863 * proccess_packet() would automatically generate the HDR*
4864 * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
4865 * We don't do this because we wish there to be no partially
4866 * built output packet if we need to suspend for asynch DNS.
4868 * We build the reply packet as we parse the message since
4869 * the parse_ipsec_sa_body emits the reply SA
4873 echo_hdr(md, TRUE, ISAKMP_NEXT_HASH);
4875 /* HASH(2) out -- first pass */
4876 START_HASH_PAYLOAD(md->rbody, ISAKMP_NEXT_SA);
4878 /* process SA (in and out) */
4880 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
4882 struct isakmp_sa sa = sapd->payload.sa;
4884 /* sa header is unchanged -- except for np */
4885 sa.isasa_np = ISAKMP_NEXT_NONCE;
4886 if (!out_struct(&sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
4887 return STF_INTERNAL_ERROR;
4889 /* parse and accept body */
4890 st->st_pfs_group = &unset_group;
4891 RETURN_STF_FAILURE(parse_ipsec_sa_body(&sapd->pbs
4892 , &sapd->payload.sa, &r_sa_pbs, FALSE, st));
4895 passert(st->st_pfs_group != &unset_group);
4897 if ((st->st_policy & POLICY_PFS) && st->st_pfs_group == NULL)
4899 loglog(RC_LOG_SERIOUS, "we require PFS but Quick I1 SA specifies no GROUP_DESCRIPTION");
4900 return STF_FAIL + NO_PROPOSAL_CHOSEN; /* ??? */
4904 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
4906 /* [ KE ] in (for PFS) */
4907 RETURN_STF_FAILURE(accept_PFS_KE(md, &st->st_gi, "Gi", "Quick Mode I1"));
4909 log("responding to Quick Mode");
4911 /**** finish reply packet: Nr [, KE ] [, IDci, IDcr ] ****/
4914 if (!build_and_ship_nonce(&st->st_nr, &md->rbody
4915 , st->st_pfs_group != NULL? ISAKMP_NEXT_KE : id_pd != NULL? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE
4917 return STF_INTERNAL_ERROR;
4919 /* [ KE ] out (for PFS) */
4921 if (st->st_pfs_group != NULL)
4923 if (!build_and_ship_KE(st, &st->st_gr, st->st_pfs_group
4924 , &md->rbody, id_pd != NULL? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE))
4925 return STF_INTERNAL_ERROR;
4927 /* MPZ-Operations might be done after sending the packet... */
4929 #ifndef DODGE_DH_MISSING_ZERO_BUG
4930 compute_dh_shared(st, st->st_gi, st->st_pfs_group);
4934 /* [ IDci, IDcr ] out */
4937 struct isakmp_ipsec_id *p = (void *)md->rbody.cur; /* UGH! */
4939 if (!out_raw(id_pd->pbs.start, pbs_room(&id_pd->pbs), &md->rbody, "IDci"))
4940 return STF_INTERNAL_ERROR;
4941 p->isaiid_np = ISAKMP_NEXT_ID;
4943 p = (void *)md->rbody.cur; /* UGH! */
4945 if (!out_raw(id_pd->next->pbs.start, pbs_room(&id_pd->next->pbs), &md->rbody, "IDcr"))
4946 return STF_INTERNAL_ERROR;
4947 p->isaiid_np = ISAKMP_NEXT_NONE;
4950 #ifdef NAT_TRAVERSAL
4951 if ((st->nat_traversal & NAT_T_WITH_NATOA) &&
4952 (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)) &&
4953 (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TRANSPORT)) {
4954 /** Send NAT-OA if our address is NATed and if we use Transport Mode */
4955 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &md->rbody, md->st)) {
4956 return STF_INTERNAL_ERROR;
4959 if ((st->nat_traversal & NAT_T_DETECTED) &&
4960 (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TRANSPORT) &&
4961 (c->that.has_client)) {
4962 /** Remove client **/
4963 addrtosubnet(&c->that.host_addr, &c->that.client);
4964 c->that.has_client = FALSE;
4968 /* Compute reply HASH(2) and insert in output */
4969 (void)quick_mode_hash12(r_hashval, r_hash_start, md->rbody.cur
4970 , st, &st->st_msgid, TRUE);
4972 /* Derive new keying material */
4973 compute_keymats(st);
4975 /* Tell the kernel to establish the new inbound SA
4976 * (unless the commit bit is set -- which we don't support).
4977 * We do this before any state updating so that
4978 * failure won't look like success.
4980 if (!install_inbound_ipsec_sa(st))
4981 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
4983 /* encrypt message, except for fixed part of header */
4985 if (!encrypt_message(&md->rbody, st))
4986 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
4992 /* Handle (the single) message from Responder in Quick Mode.
4993 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
4995 * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
4996 * Installs inbound and outbound IPsec SAs, routing, etc.
4999 quick_inR1_outI2(struct msg_digest *md)
5001 struct state *const st = md->st;
5002 const struct connection *c = st->st_connection;
5006 , quick_mode_hash12(hash_val, hash_pbs->roof, md->message_pbs.roof
5007 , st, &st->st_msgid, TRUE)
5008 , "HASH(2)", "Quick R1");
5012 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
5014 RETURN_STF_FAILURE(parse_ipsec_sa_body(&sa_pd->pbs
5015 , &sa_pd->payload.sa, NULL, TRUE, st));
5019 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
5021 /* [ KE ] in (for PFS) */
5022 RETURN_STF_FAILURE(accept_PFS_KE(md, &st->st_gr, "Gr", "Quick Mode R1"));
5024 if (st->st_pfs_group != NULL)
5026 compute_dh_shared(st, st->st_gr, st->st_pfs_group);
5027 #ifdef DODGE_DH_MISSING_ZERO_BUG
5028 if (st->st_shared.ptr[0] == 0)
5029 return STF_REPLACE_DOOMED_EXCHANGE;
5033 /* [ IDci, IDcr ] in; these must match what we sent */
5036 struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
5040 /* ??? we are assuming IPSEC_DOI */
5042 /* IDci (we are initiator) */
5044 if (!check_net_id(&id_pd->payload.ipsec_id, &id_pd->pbs
5045 , &st->st_myuserprotoid, &st->st_myuserport
5046 , &st->st_connection->this.client
5048 return STF_FAIL + INVALID_ID_INFORMATION;
5050 /* IDcr (responder is peer) */
5052 if (!check_net_id(&id_pd->next->payload.ipsec_id, &id_pd->next->pbs
5053 , &st->st_peeruserprotoid, &st->st_peeruserport
5054 , &st->st_connection->that.client
5056 return STF_FAIL + INVALID_ID_INFORMATION;
5060 /* No IDci, IDcr: we must check that the defaults match our proposal.
5061 * Parallels a sequence of assignments in quick_outI1.
5063 if (!subnetishost(&c->this.client) || !subnetishost(&c->that.client))
5065 loglog(RC_LOG_SERIOUS, "IDci, IDcr payloads missing in message"
5066 " but default does not match proposal");
5067 return STF_FAIL + INVALID_ID_INFORMATION;
5072 #ifdef NAT_TRAVERSAL
5073 if ((st->nat_traversal & NAT_T_DETECTED) &&
5074 (st->nat_traversal & NAT_T_WITH_NATOA)) {
5075 nat_traversal_natoa_lookup(md);
5079 /* ??? We used to copy the accepted proposal into the state, but it was
5080 * never used. From sa_pd->pbs.start, length pbs_room(&sa_pd->pbs).
5083 /**************** build reply packet HDR*, HASH(3) ****************/
5087 /* HASH(3) out -- since this is the only content, no passes needed */
5089 u_char /* set by START_HASH_PAYLOAD: */
5090 *r_hashval, /* where in reply to jam hash value */
5091 *r_hash_start; /* start of what is to be hashed */
5093 START_HASH_PAYLOAD(md->rbody, ISAKMP_NEXT_NONE);
5094 (void)quick_mode_hash3(r_hashval, st);
5097 /* Derive new keying material */
5098 compute_keymats(st);
5100 /* Tell the kernel to establish the inbound, outbound, and routing part
5101 * of the new SA (unless the commit bit is set -- which we don't support).
5102 * We do this before any state updating so that
5103 * failure won't look like success.
5105 if (!install_ipsec_sa(st, TRUE))
5106 return STF_INTERNAL_ERROR;
5108 /* encrypt message, except for fixed part of header */
5110 if (!encrypt_message(&md->rbody, st))
5111 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
5113 st->st_connection->newest_ipsec_sa = st->st_serialno;
5115 /* note (presumed) success */
5116 if (c->gw_info != NULL)
5117 c->gw_info->last_worked_time = now();
5119 if (st->st_connection->kind == CK_PERMANENT && st->st_connection->dpd_delay)
5125 /* Handle last message of Quick Mode.
5126 * HDR*, HASH(3) -> done
5127 * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
5128 * Installs outbound IPsec SAs, routing, etc.
5131 quick_inI2(struct msg_digest *md)
5133 struct state *const st = md->st;
5136 CHECK_QUICK_HASH(md, quick_mode_hash3(hash_val, st)
5137 , "HASH(3)", "Quick I2");
5139 /* Tell the kernel to establish the outbound and routing part of the new SA
5140 * (the previous state established inbound)
5141 * (unless the commit bit is set -- which we don't support).
5142 * We do this before any state updating so that
5143 * failure won't look like success.
5145 if (!install_ipsec_sa(st, FALSE))
5146 return STF_INTERNAL_ERROR;
5148 st->st_connection->newest_ipsec_sa = st->st_serialno;
5150 update_iv(st); /* not actually used, but tidy */
5152 /* note (presumed) success */
5154 struct gw_info *gw = st->st_connection->gw_info;
5157 gw->last_worked_time = now();
5160 if (st->st_connection->kind == CK_PERMANENT && st->st_connection->dpd_delay)
5167 send_isakmp_notification(struct state *st,
5168 u_int16_t type, const void *data, size_t len)
5173 u_char old_new_iv[MAX_DIGEST_LEN];
5174 u_char old_iv[MAX_DIGEST_LEN];
5176 *r_hashval, /* where in reply to jam hash value */
5177 *r_hash_start; /* start of what is to be hashed */
5179 msgid = generate_msgid(st);
5181 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "ISAKMP notify");
5185 struct isakmp_hdr hdr;
5187 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
5188 hdr.isa_np = ISAKMP_NEXT_HASH;
5189 hdr.isa_xchg = ISAKMP_XCHG_INFO;
5190 hdr.isa_msgid = msgid;
5191 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
5192 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
5193 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
5194 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
5198 /* HASH -- create and note space to be filled later */
5199 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_N);
5203 pb_stream notify_pbs;
5204 struct isakmp_notification isan;
5206 isan.isan_np = ISAKMP_NEXT_NONE;
5207 isan.isan_doi = ISAKMP_DOI_IPSEC;
5208 isan.isan_protoid = PROTO_ISAKMP;
5209 isan.isan_spisize = COOKIE_SIZE * 2;
5210 isan.isan_type = type;
5211 if (!out_struct(&isan, &isakmp_notification_desc, &rbody, ¬ify_pbs))
5212 return STF_INTERNAL_ERROR;
5213 if (!out_raw(st->st_icookie, COOKIE_SIZE, ¬ify_pbs, "notify icookie"))
5214 return STF_INTERNAL_ERROR;
5215 if (!out_raw(st->st_rcookie, COOKIE_SIZE, ¬ify_pbs, "notify rcookie"))
5216 return STF_INTERNAL_ERROR;
5217 if (data != NULL && len > 0)
5218 if (!out_raw(data, len, ¬ify_pbs, "notify data"))
5219 return STF_INTERNAL_ERROR;
5220 close_output_pbs(¬ify_pbs);
5224 /* finish computing HASH */
5225 struct hmac_ctx ctx;
5227 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
5228 hmac_update(&ctx, (const u_char *) &msgid, sizeof(msgid_t));
5229 hmac_update(&ctx, r_hash_start, rbody.cur-r_hash_start);
5230 hmac_final(r_hashval, &ctx);
5233 DBG_log("HASH computed:");
5234 DBG_dump("", r_hashval, ctx.hmac_digest_size));
5237 /* save old IV (this prevents from copying a whole new state object
5238 * for NOTIFICATION / DELETE messages we don't need to maintain a state
5239 * because there are no retransmissions...
5242 memcpy(old_new_iv, st->st_new_iv, st->st_new_iv_len);
5243 memcpy(old_iv, st->st_iv, st->st_iv_len);
5244 init_phase2_iv(st, &msgid);
5246 if (!encrypt_message(&rbody, st))
5247 return STF_INTERNAL_ERROR;
5250 chunk_t saved_tpacket = st->st_tpacket;
5252 setchunk(st->st_tpacket, reply.start, pbs_offset(&reply));
5253 send_packet(st, "ISAKMP notify");
5254 st->st_tpacket = saved_tpacket;
5257 /* get back old IV for this state */
5258 memcpy(st->st_new_iv, old_new_iv, st->st_new_iv_len);
5259 memcpy(st->st_iv, old_iv, st->st_iv_len);
5265 dpd_init(struct state *st)
5269 /* find the related Phase 1 state */
5270 p1st = find_state(st->st_icookie, st->st_rcookie,
5271 &st->st_connection->that.host_addr, 0);
5273 loglog(RC_LOG_SERIOUS, "could not find phase 1 state for DPD");
5274 else if (p1st->st_dpd)
5275 event_schedule(EVENT_DPD, st->st_connection->dpd_delay, st);
5279 dpd_outI(struct state *p2st)
5284 time_t delay = p2st->st_connection->dpd_delay;
5285 time_t timeout = p2st->st_connection->dpd_timeout;
5287 /* find the related Phase 1 state */
5288 st = find_phase1_state(p2st->st_connection, FALSE);
5291 loglog(RC_LOG_SERIOUS, "could not find newest phase 1 state for DPD");
5297 /* If an R_U_THERE has been sent or received recently, then
5298 * base the resend time on that. */
5300 if (tm < st->st_last_dpd + delay)
5302 event_schedule(EVENT_DPD, st->st_last_dpd + delay - tm, p2st);
5303 /* If there is still a timeout for the last R_U_THERE sent,
5304 * and the timeout is greater than ours, then reduce it. */
5305 if (st->st_dpd_event != NULL
5306 && st->st_dpd_event->ev_time > st->st_last_dpd + timeout)
5308 delete_dpd_event(st);
5309 event_schedule(EVENT_DPD_TIMEOUT, st->st_last_dpd + timeout - tm, st);
5314 event_schedule(EVENT_DPD, delay, p2st);
5316 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5319 if (!st->st_dpd_seqno)
5321 /* Get a non-zero random value that has room to grow */
5322 get_rnd_bytes((u_char *)&st->st_dpd_seqno, sizeof(st->st_dpd_seqno));
5323 st->st_dpd_seqno &= 0x7fff;
5326 seqno = htonl(st->st_dpd_seqno);
5327 if (send_isakmp_notification(st, R_U_THERE, &seqno, sizeof(seqno)) != STF_IGNORE)
5329 loglog(RC_LOG_SERIOUS, "could not send R_U_THERE");
5333 st->st_dpd_expectseqno = st->st_dpd_seqno++;
5334 st->st_last_dpd = tm;
5335 /* Only schedule a new timeout if there isn't one currently,
5336 * or if it would be sooner than the current timeout. */
5337 if (st->st_dpd_event == NULL
5338 || st->st_dpd_event->ev_time > tm + timeout)
5340 delete_dpd_event(st);
5341 event_schedule(EVENT_DPD_TIMEOUT, timeout, st);
5346 dpd_inI_outR(struct state *st, struct isakmp_notification *const n, pb_stream *n_pbs)
5351 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5353 loglog(RC_LOG_SERIOUS, "recevied R_U_THERE for unestablished ISKAMP SA");
5357 if (n->isan_spisize != COOKIE_SIZE * 2 || pbs_left(n_pbs) < COOKIE_SIZE * 2)
5359 loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid SPI length (%d)", n->isan_spisize);
5363 if (memcmp(n_pbs->cur, st->st_icookie, COOKIE_SIZE) != 0)
5365 loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid icookie");
5368 n_pbs->cur += COOKIE_SIZE;
5370 if (memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0)
5372 loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid rcookie");
5375 n_pbs->cur += COOKIE_SIZE;
5377 if (pbs_left(n_pbs) != sizeof(seqno))
5379 loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid data length (%d)", pbs_left(n_pbs));
5383 seqno = ntohl(*(u_int32_t *)n_pbs->cur);
5384 if (st->st_dpd_peerseqno && seqno <= st->st_dpd_peerseqno) {
5385 loglog(RC_LOG_SERIOUS, "received old or duplicate R_U_THERE");
5389 st->st_dpd_peerseqno = seqno;
5390 delete_dpd_event(st);
5392 if (send_isakmp_notification(st, R_U_THERE_ACK, n_pbs->cur, pbs_left(n_pbs)) != STF_IGNORE)
5394 loglog(RC_LOG_SERIOUS, "could not send R_U_THERE_ACK");
5398 st->st_last_dpd = tm;
5403 dpd_inR(struct state *st, struct isakmp_notification *const n, pb_stream *n_pbs)
5406 u_int8_t tmp[COOKIE_SIZE];
5408 memset(tmp, 0, sizeof(tmp));
5410 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5412 loglog(RC_LOG_SERIOUS, "recevied R_U_THERE_ACK for unestablished ISKAMP SA");
5416 if (n->isan_spisize != COOKIE_SIZE * 2 || pbs_left(n_pbs) < COOKIE_SIZE * 2)
5418 loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid SPI length (%d)", n->isan_spisize);
5422 if (memcmp(n_pbs->cur, st->st_icookie, COOKIE_SIZE) != 0 && memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0)
5424 loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid icookie");
5427 n_pbs->cur += COOKIE_SIZE;
5428 if (memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0 && memcmp(n_pbs->cur, &tmp, COOKIE_SIZE) != 0)
5430 loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid rcookie");
5433 n_pbs->cur += COOKIE_SIZE;
5435 if (pbs_left(n_pbs) != sizeof(seqno))
5437 loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid data length (%d)", pbs_left(n_pbs));
5441 seqno = ntohl(*(u_int32_t *)n_pbs->cur);
5442 if (!st->st_dpd_expectseqno && seqno != st->st_dpd_expectseqno) {
5443 loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has unexpected sequence number");
5447 st->st_dpd_expectseqno = 0;
5448 delete_dpd_event(st);
5453 dpd_timeout(struct state *st)
5455 struct connection *c = st->st_connection;
5457 loglog(RC_LOG_SERIOUS, "timeout waiting for DPD ack, replacing SA");
5458 terminate_connections_by_peer(c);
5459 initiate_connections_by_peer(c);