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
15 * RCSID $Id: ipsec_doi.c,v 1.39 2006/04/22 21:59:20 as Exp $
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/queue.h>
29 #include <sys/time.h> /* for gettimeofday */
32 #include <ipsec_policy.h>
34 #include "constants.h"
43 #include "smartcard.h"
44 #include "connections.h"
47 #include "demux.h" /* needs packet.h */
48 #include "adns.h" /* needs <resolv.h> */
49 #include "dnskey.h" /* needs keys.h and adns.h */
57 #include "ipsec_doi.h" /* needs demux.h and state.h */
65 #include "crypto.h" /* requires sha1.h and md5.h */
69 #include "kernel_alg.h"
70 #include "nat_traversal.h"
74 * are we sending Pluto's Vendor ID?
77 #define SEND_PLUTO_VID 1
79 #define SEND_PLUTO_VID 0
80 #endif /* !VENDORID */
83 * are we sending a Cisco Unity VID?
86 #define SEND_CISCO_UNITY_VID 1
87 #else /* !CISCO_QUIRKS */
88 #define SEND_CISCO_UNITY_VID 0
89 #endif /* !CISCO_QUIRKS */
91 /* MAGIC: perform f, a function that returns notification_t
92 * and return from the ENCLOSING stf_status returning function if it fails.
94 #define RETURN_STF_FAILURE(f) \
95 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
97 /* create output HDR as replica of input HDR */
99 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
101 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
103 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
105 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
106 /* some day, we may have to set r_hdr.isa_version */
108 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
109 impossible(); /* surely must have room and be well-formed */
112 /* Compute DH shared secret from our local secret and the peer's public value.
113 * We make the leap that the length should be that of the group
114 * (see quoted passage at start of ACCEPT_KE).
117 compute_dh_shared(struct state
*st
, const chunk_t g
118 , const struct oakley_group_desc
*group
)
120 MP_INT mp_g
, mp_shared
;
121 struct timeval tv0
, tv1
;
122 unsigned long tv_diff
;
124 gettimeofday(&tv0
, NULL
);
125 passert(st
->st_sec_in_use
);
126 n_to_mpz(&mp_g
, g
.ptr
, g
.len
);
127 mpz_init(&mp_shared
);
128 mpz_powm(&mp_shared
, &mp_g
, &st
->st_sec
, group
->modulus
);
130 freeanychunk(st
->st_shared
); /* happens in odd error cases */
131 st
->st_shared
= mpz_to_n(&mp_shared
, group
->bytes
);
132 mpz_clear(&mp_shared
);
133 gettimeofday(&tv1
, NULL
);
134 tv_diff
=(tv1
.tv_sec
- tv0
.tv_sec
) * 1000000 + (tv1
.tv_usec
- tv0
.tv_usec
);
136 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
137 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
140 /* if took more than 200 msec ... */
141 if (tv_diff
> 200000) {
142 loglog(RC_LOG_SERIOUS
, "WARNING: compute_dh_shared(): for %s took "
144 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
148 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
151 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
152 * the corresponding public value (g). This is emitted as a KE payload.
155 build_and_ship_KE(struct state
*st
, chunk_t
*g
156 , const struct oakley_group_desc
*group
, pb_stream
*outs
, u_int8_t np
)
158 if (!st
->st_sec_in_use
)
160 u_char tmp
[LOCALSECRETSIZE
];
163 get_rnd_bytes(tmp
, LOCALSECRETSIZE
);
164 st
->st_sec_in_use
= TRUE
;
165 n_to_mpz(&st
->st_sec
, tmp
, LOCALSECRETSIZE
);
168 mpz_powm(&mp_g
, &groupgenerator
, &st
->st_sec
, group
->modulus
);
169 freeanychunk(*g
); /* happens in odd error cases */
170 *g
= mpz_to_n(&mp_g
, group
->bytes
);
173 DBG_dump("Local DH secret:\n", tmp
, LOCALSECRETSIZE
);
174 DBG_dump_chunk("Public DH value sent:\n", *g
));
176 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
181 * Check and accept DH public value (Gi or Gr) from peer's message.
182 * According to RFC2409 "The Internet key exchange (IKE)" 5:
183 * The Diffie-Hellman public value passed in a KE payload, in either
184 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
185 * Diffie-Hellman group enforced, if necessary, by pre-pending the
188 static notification_t
189 accept_KE(chunk_t
*dest
, const char *val_name
190 , const struct oakley_group_desc
*gr
193 if (pbs_left(pbs
) != gr
->bytes
)
195 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
196 , (unsigned) pbs_left(pbs
), (unsigned) gr
->bytes
);
197 /* XXX Could send notification back */
198 return INVALID_KEY_INFORMATION
;
200 clonereplacechunk(*dest
, pbs
->cur
, pbs_left(pbs
), val_name
);
201 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
202 return NOTHING_WRONG
;
207 * Check and accept optional Quick Mode KE payload for PFS.
208 * Extends ACCEPT_PFS to check whether KE is allowed or required.
210 static notification_t
211 accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
212 , const char *val_name
, const char *msg_name
)
214 struct state
*st
= md
->st
;
215 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
219 if (st
->st_pfs_group
!= NULL
)
221 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
222 return INVALID_KEY_INFORMATION
;
227 if (st
->st_pfs_group
== NULL
)
229 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
231 return INVALID_KEY_INFORMATION
;
233 if (ke_pd
->next
!= NULL
)
235 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
236 return INVALID_KEY_INFORMATION
; /* ??? */
238 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
240 return NOTHING_WRONG
;
244 build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
248 setchunk(*n
, alloc_bytes(DEFAULT_NONCE_SIZE
, name
), DEFAULT_NONCE_SIZE
);
249 get_rnd_bytes(n
->ptr
, DEFAULT_NONCE_SIZE
);
250 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
254 collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
256 struct connection
*d
= find_host_connection(&md
->iface
->addr
257 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
259 for (; d
!= NULL
; d
= d
->hp_next
)
261 /* must be a road warrior connection */
262 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
263 && d
->spd
.that
.ca
.ptr
!= NULL
)
266 bool new_entry
= TRUE
;
268 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
270 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
278 gn
= alloc_thing(generalName_t
, "generalName");
279 gn
->kind
= GN_DIRECTORY_NAME
;
280 gn
->name
= d
->spd
.that
.ca
;
290 build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
, u_int8_t np
)
293 struct isakmp_cr cr_hd
;
295 cr_hd
.isacr_type
= type
;
297 /* build CR header */
298 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
303 /* build CR body containing the distinguished name of the CA */
304 if (!out_chunk(ca
, &cr_pbs
, "CA"))
307 close_output_pbs(&cr_pbs
);
311 /* Send a notification to the peer. We could decide
312 * whether to send the notification, based on the type and the
313 * destination, if we care to.
316 send_notification(struct state
*sndst
, u_int16_t type
, struct state
*encst
,
317 msgid_t msgid
, u_char
*icookie
, u_char
*rcookie
,
318 u_char
*spi
, size_t spisize
, u_char protoid
)
321 pb_stream pbs
, r_hdr_pbs
;
322 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
323 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
325 passert((sndst
) && (sndst
->st_connection
));
327 plog("sending %snotification %s to %s:%u"
328 , encst ?
"encrypted " : ""
329 , enum_name(¬ification_names
, type
)
330 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
331 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
333 memset(buffer
, 0, sizeof(buffer
));
334 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
338 struct isakmp_hdr hdr
;
340 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
341 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
342 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
343 hdr
.isa_msgid
= msgid
;
344 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
346 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
348 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
349 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
353 /* HASH -- value to be filled later */
357 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
360 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
362 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
364 close_output_pbs(&hash_pbs
);
365 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
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
);
395 DBG_log("HASH computed:");
396 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
400 /* Encrypt message (preserve st_iv and st_new_iv) */
403 u_char old_iv
[MAX_DIGEST_LEN
];
404 u_char new_iv
[MAX_DIGEST_LEN
];
406 u_int old_iv_len
= encst
->st_iv_len
;
407 u_int new_iv_len
= encst
->st_new_iv_len
;
409 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
412 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
413 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
415 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
417 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
418 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
420 init_phase2_iv(encst
, &msgid
);
421 if (!encrypt_message(&r_hdr_pbs
, encst
))
424 /* restore preserved st_iv and st_new_iv */
425 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
426 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
427 encst
->st_iv_len
= old_iv_len
;
428 encst
->st_new_iv_len
= new_iv_len
;
432 close_output_pbs(&r_hdr_pbs
);
435 /* Send packet (preserve st_tpacket) */
437 chunk_t saved_tpacket
= sndst
->st_tpacket
;
439 setchunk(sndst
->st_tpacket
, pbs
.start
, pbs_offset(&pbs
));
440 send_packet(sndst
, "ISAKMP notify");
441 sndst
->st_tpacket
= saved_tpacket
;
446 send_notification_from_state(struct state
*st
, enum state_kind state
,
453 if (state
== STATE_UNDEFINED
)
454 state
= st
->st_state
;
458 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
459 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
)))
461 loglog(RC_LOG_SERIOUS
,
462 "no Phase1 state for Quick mode notification");
465 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
466 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
468 else if (IS_ISAKMP_ENCRYPTED(state
) && st
->st_enc_key
.ptr
!= NULL
)
470 send_notification(st
, type
, st
, generate_msgid(st
),
471 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
475 /* no ISAKMP SA established - don't encrypt notification */
476 send_notification(st
, type
, NULL
, 0,
477 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
482 send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
485 * Create a dummy state to be able to use send_packet in
489 * st_connection->that.host_addr
490 * st_connection->that.host_port
491 * st_connection->interface
494 struct connection cnx
;
498 memset(&st
, 0, sizeof(st
));
499 memset(&cnx
, 0, sizeof(cnx
));
500 st
.st_connection
= &cnx
;
501 cnx
.spd
.that
.host_addr
= md
->sender
;
502 cnx
.spd
.that
.host_port
= md
->sender_port
;
503 cnx
.interface
= md
->iface
;
505 send_notification(&st
, type
, NULL
, 0,
506 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
509 /* Send a Delete Notification to announce deletion of ISAKMP SA or
510 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
511 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
514 send_delete(struct state
*st
)
521 ip_said said
[EM_MAXRELSPIS
];
524 *r_hashval
, /* where in reply to jam hash value */
525 *r_hash_start
; /* start of what is to be hashed */
526 bool isakmp_sa
= FALSE
;
528 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
530 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
533 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
537 if (st
->st_ah
.present
)
539 ns
->spi
= st
->st_ah
.our_spi
;
540 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
541 ns
->proto
= PROTO_IPSEC_AH
;
544 if (st
->st_esp
.present
)
546 ns
->spi
= st
->st_esp
.our_spi
;
547 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
548 ns
->proto
= PROTO_IPSEC_ESP
;
552 passert(ns
!= said
); /* there must be some SAs to delete */
554 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
561 return; /* nothing to do */
564 msgid
= generate_msgid(p1st
);
567 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
571 struct isakmp_hdr hdr
;
573 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
574 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
575 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
576 hdr
.isa_msgid
= msgid
;
577 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
578 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
579 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
580 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
584 /* HASH -- value to be filled later */
588 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
590 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
591 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
593 close_output_pbs(&hash_pbs
);
594 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
597 /* Delete Payloads */
601 struct isakmp_delete isad
;
602 u_char isakmp_spi
[2*COOKIE_SIZE
];
604 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
605 isad
.isad_np
= ISAKMP_NEXT_NONE
;
606 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
607 isad
.isad_protoid
= PROTO_ISAKMP
;
610 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
611 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
613 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
614 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
616 close_output_pbs(&del_pbs
);
624 struct isakmp_delete isad
;
627 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
628 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
629 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
630 isad
.isad_protoid
= ns
->proto
;
633 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
634 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
636 close_output_pbs(&del_pbs
);
640 /* calculate hash value and patch into Hash Payload */
643 hmac_init_chunk(&ctx
, p1st
->st_oakley
.hasher
, p1st
->st_skeyid_a
);
644 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
645 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
646 hmac_final(r_hashval
, &ctx
);
649 DBG_log("HASH(1) computed:");
650 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
654 /* Do a dance to avoid needing a new state object.
655 * We use the Phase 1 State. This is the one with right
657 * The tricky bits are:
658 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
659 * - we need to preserve (save/restore) st_tpacket.
662 u_char old_iv
[MAX_DIGEST_LEN
];
663 chunk_t saved_tpacket
= p1st
->st_tpacket
;
665 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
666 init_phase2_iv(p1st
, &msgid
);
668 if (!encrypt_message(&r_hdr_pbs
, p1st
))
671 setchunk(p1st
->st_tpacket
, reply_pbs
.start
, pbs_offset(&reply_pbs
));
672 send_packet(p1st
, "delete notify");
673 p1st
->st_tpacket
= saved_tpacket
;
675 /* get back old IV for this state */
676 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
681 accept_delete(struct state
*st
, struct msg_digest
*md
, struct payload_digest
*p
)
683 struct isakmp_delete
*d
= &(p
->payload
.delete);
689 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
693 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
695 /* can't happen (if msg is encrypt), but just to be sure */
696 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
697 "ISAKMP SA not established");
701 if (d
->isad_nospi
== 0)
703 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
707 switch (d
->isad_protoid
)
710 sizespi
= 2 * COOKIE_SIZE
;
713 case PROTO_IPSEC_ESP
:
714 sizespi
= sizeof(ipsec_spi_t
);
717 /* nothing interesting to delete */
720 loglog(RC_LOG_SERIOUS
721 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
722 , enum_show(&protocol_names
, d
->isad_protoid
));
726 if (d
->isad_spisize
!= sizespi
)
728 loglog(RC_LOG_SERIOUS
729 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
730 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
734 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
736 loglog(RC_LOG_SERIOUS
737 , "ignoring Delete SA payload: invalid payload size");
741 for (i
= 0; i
< d
->isad_nospi
; i
++)
743 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
745 if (d
->isad_protoid
== PROTO_ISAKMP
)
750 struct state
*dst
= find_state(spi
/*iCookie*/
751 , spi
+COOKIE_SIZE
/*rCookie*/
752 , &st
->st_connection
->spd
.that
.host_addr
757 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
758 "ISAKMP SA not found (maybe expired)");
760 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
762 /* we've not authenticated the relevant identities */
763 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
764 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
768 struct connection
*oldc
;
770 oldc
= cur_connection
;
771 set_cur_connection(dst
->st_connection
);
773 if (nat_traversal_enabled
)
774 nat_traversal_change_port_lookup(md
, dst
);
776 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
777 "deleting ISAKMP State #%lu", dst
->st_serialno
);
779 set_cur_connection(oldc
);
788 struct state
*dst
= find_phase2_state_to_delete(st
790 , *(ipsec_spi_t
*)spi
/* network order */
795 loglog(RC_LOG_SERIOUS
796 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
797 , enum_show(&protocol_names
, d
->isad_protoid
)
798 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
799 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
803 struct connection
*rc
= dst
->st_connection
;
804 struct connection
*oldc
;
806 oldc
= cur_connection
;
807 set_cur_connection(rc
);
809 if (nat_traversal_enabled
)
810 nat_traversal_change_port_lookup(md
, dst
);
812 if (rc
->newest_ipsec_sa
== dst
->st_serialno
813 && (rc
->policy
& POLICY_UP
))
815 /* Last IPSec SA for a permanent connection that we
816 * have initiated. Replace it in a few seconds.
818 * Useful if the other peer is rebooting.
820 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
821 if (dst
->st_event
!= NULL
822 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
823 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
825 /* Patch from Angus Lees to ignore retransmited
828 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
829 "already replacing IPSEC State #%lu in %d seconds"
830 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
834 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
835 "replace IPSEC State #%lu in %d seconds"
836 , dst
->st_serialno
, DELETE_SA_DELAY
);
837 dst
->st_margin
= DELETE_SA_DELAY
;
839 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
844 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
845 "deleting IPSEC State #%lu"
846 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
851 /* reset connection */
852 set_cur_connection(oldc
);
858 /* The whole message must be a multiple of 4 octets.
859 * I'm not sure where this is spelled out, but look at
860 * rfc2408 3.6 Transform Payload.
861 * Note: it talks about 4 BYTE boundaries!
864 close_message(pb_stream
*pbs
)
866 size_t padding
= pad_up(pbs_offset(pbs
), 4);
869 (void) out_zero(padding
, pbs
, "message padding");
870 close_output_pbs(pbs
);
873 /* Initiate an Oakley Main Mode exchange.
875 * Note: this is not called from demux.c
878 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
879 , lset_t policy
, unsigned long try)
881 struct state
*st
= new_state();
882 pb_stream reply
; /* not actually a reply, but you know what I mean */
885 int vids_to_send
= 0;
887 /* set up new state */
888 st
->st_connection
= c
;
889 set_cur_state(st
); /* we must reset before exit */
890 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
891 st
->st_whack_sock
= whack_sock
;
893 st
->st_state
= STATE_MAIN_I1
;
895 /* determine how many Vendor ID payloads we will be sending */
898 if (SEND_CISCO_UNITY_VID
)
900 if (c
->spd
.this.cert
.type
== CERT_PGP
)
902 /* always send XAUTH Vendor ID */
904 /* always send DPD Vendor ID */
906 if (nat_traversal_enabled
)
909 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
911 insert_state(st
); /* needs cookies, connection, and msgid (0) */
913 if (HAS_IPSEC_POLICY(policy
))
914 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
915 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
917 if (predecessor
== NULL
)
918 plog("initiating Main Mode");
920 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
923 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
927 struct isakmp_hdr hdr
;
929 zero(&hdr
); /* default to 0 */
930 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
931 hdr
.isa_np
= ISAKMP_NEXT_SA
;
932 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
933 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
934 /* R-cookie, flags and MessageID are left zero */
936 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
939 return STF_INTERNAL_ERROR
;
945 u_char
*sa_start
= rbody
.cur
;
946 lset_t auth_policy
= policy
& POLICY_ID_AUTH_MASK
;
948 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
949 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
952 return STF_INTERNAL_ERROR
;
955 /* save initiator SA for later HASH */
956 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
957 clonetochunk(st
->st_p1isa
, sa_start
, rbody
.cur
- sa_start
958 , "sa in main_outI1");
961 /* if enabled send Pluto Vendor ID */
964 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
965 , &rbody
, VID_STRONGSWAN
))
968 return STF_INTERNAL_ERROR
;
972 /* if enabled send Cisco Unity Vendor ID */
973 if (SEND_CISCO_UNITY_VID
)
975 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
976 , &rbody
, VID_CISCO_UNITY
))
979 return STF_INTERNAL_ERROR
;
982 /* if we have an OpenPGP certificate we assume an
983 * OpenPGP peer and have to send the Vendor ID
985 if (c
->spd
.this.cert
.type
== CERT_PGP
)
987 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
988 , &rbody
, VID_OPENPGP
))
991 return STF_INTERNAL_ERROR
;
995 /* Announce our ability to do eXtended AUTHentication to the peer */
996 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
997 , &rbody
, VID_MISC_XAUTH
))
1000 return STF_INTERNAL_ERROR
;
1003 /* Announce our ability to do Dead Peer Detection to the peer */
1005 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1006 , &rbody
, VID_MISC_DPD
))
1009 return STF_INTERNAL_ERROR
;
1013 if (nat_traversal_enabled
)
1015 /* Add supported NAT-Traversal VID */
1016 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1020 return STF_INTERNAL_ERROR
;
1024 close_message(&rbody
);
1025 close_output_pbs(&reply
);
1027 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
1028 , "reply packet for main_outI1");
1032 send_packet(st
, "main_outI1");
1034 /* Set up a retransmission event, half a minute henceforth */
1036 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1038 if (predecessor
!= NULL
)
1040 update_pending(predecessor
, st
);
1041 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1042 , "%s: initiate, replacing #%lu"
1043 , enum_name(&state_names
, st
->st_state
)
1044 , predecessor
->st_serialno
);
1048 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1049 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1056 ipsecdoi_initiate(int whack_sock
1057 , struct connection
*c
1060 , so_serial_t replacing
)
1062 /* If there's already an ISAKMP SA established, use that and
1063 * go directly to Quick Mode. We are even willing to use one
1064 * that is still being negotiated, but only if we are the Initiator
1065 * (thus we can be sure that the IDs are not going to change;
1066 * other issues around intent might matter).
1067 * Note: there is no way to initiate with a Road Warrior.
1069 struct state
*st
= find_phase1_state(c
1070 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1074 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1076 else if (HAS_IPSEC_POLICY(policy
))
1078 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1080 /* leave our Phase 2 negotiation pending */
1081 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1085 /* ??? we assume that peer_nexthop_sin isn't important:
1086 * we already have it from when we negotiated the ISAKMP SA!
1087 * It isn't clear what to do with the error return.
1089 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1094 close_any(whack_sock
);
1098 /* Replace SA with a fresh one that is similar
1100 * Shares some logic with ipsecdoi_initiate, but not the same!
1101 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1102 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1103 * ISAKMP SA if needed.
1104 * - duplicate whack fd, if live.
1105 * Does not delete the old state -- someone else will do that.
1108 ipsecdoi_replace(struct state
*st
, unsigned long try)
1110 int whack_sock
= dup_any(st
->st_whack_sock
);
1111 lset_t policy
= st
->st_policy
;
1113 if (IS_PHASE1(st
->st_state
))
1115 passert(!HAS_IPSEC_POLICY(policy
));
1116 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1120 /* Add features of actual old state to policy. This ensures
1121 * that rekeying doesn't downgrade security. I admit that
1122 * this doesn't capture everything.
1124 if (st
->st_pfs_group
!= NULL
)
1125 policy
|= POLICY_PFS
;
1126 if (st
->st_ah
.present
)
1128 policy
|= POLICY_AUTHENTICATE
;
1129 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1130 policy
|= POLICY_TUNNEL
;
1132 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1134 policy
|= POLICY_ENCRYPT
;
1135 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1136 policy
|= POLICY_TUNNEL
;
1138 if (st
->st_ipcomp
.present
)
1140 policy
|= POLICY_COMPRESS
;
1141 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1142 policy
|= POLICY_TUNNEL
;
1144 passert(HAS_IPSEC_POLICY(policy
));
1145 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1150 /* SKEYID for preshared keys.
1151 * See draft-ietf-ipsec-ike-01.txt 4.1
1154 skeyid_preshared(struct state
*st
)
1156 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1160 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1165 struct hmac_ctx ctx
;
1167 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, *pss
);
1168 hmac_update_chunk(&ctx
, st
->st_ni
);
1169 hmac_update_chunk(&ctx
, st
->st_nr
);
1170 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_preshared()", &ctx
);
1176 skeyid_digisig(struct state
*st
)
1178 struct hmac_ctx ctx
;
1181 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1182 * so we have to build a temporary concatentation.
1184 nir
.len
= st
->st_ni
.len
+ st
->st_nr
.len
;
1185 nir
.ptr
= alloc_bytes(nir
.len
, "Ni + Nr in skeyid_digisig");
1186 memcpy(nir
.ptr
, st
->st_ni
.ptr
, st
->st_ni
.len
);
1187 memcpy(nir
.ptr
+st
->st_ni
.len
, st
->st_nr
.ptr
, st
->st_nr
.len
);
1188 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, nir
);
1191 hmac_update_chunk(&ctx
, st
->st_shared
);
1192 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_digisig()", &ctx
);
1196 /* Generate the SKEYID_* and new IV
1197 * See draft-ietf-ipsec-ike-01.txt 4.1
1200 generate_skeyids_iv(struct state
*st
)
1202 /* Generate the SKEYID */
1203 switch (st
->st_oakley
.auth
)
1205 case OAKLEY_PRESHARED_KEY
:
1206 case XAUTHInitPreShared
:
1207 case XAUTHRespPreShared
:
1208 if (!skeyid_preshared(st
))
1212 case OAKLEY_RSA_SIG
:
1215 if (!skeyid_digisig(st
))
1219 case OAKLEY_DSS_SIG
:
1222 case OAKLEY_RSA_ENC
:
1223 case OAKLEY_RSA_ENC_REV
:
1224 case OAKLEY_ELGAMAL_ENC
:
1225 case OAKLEY_ELGAMAL_ENC_REV
:
1229 bad_case(st
->st_oakley
.auth
);
1232 /* generate SKEYID_* from SKEYID */
1234 struct hmac_ctx ctx
;
1236 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1239 hmac_update_chunk(&ctx
, st
->st_shared
);
1240 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1241 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1242 hmac_update(&ctx
, "\0", 1);
1243 hmac_final_chunk(st
->st_skeyid_d
, "st_skeyid_d in generate_skeyids_iv()", &ctx
);
1247 hmac_update_chunk(&ctx
, st
->st_skeyid_d
);
1248 hmac_update_chunk(&ctx
, st
->st_shared
);
1249 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1250 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1251 hmac_update(&ctx
, "\1", 1);
1252 hmac_final_chunk(st
->st_skeyid_a
, "st_skeyid_a in generate_skeyids_iv()", &ctx
);
1256 hmac_update_chunk(&ctx
, st
->st_skeyid_a
);
1257 hmac_update_chunk(&ctx
, st
->st_shared
);
1258 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1259 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1260 hmac_update(&ctx
, "\2", 1);
1261 hmac_final_chunk(st
->st_skeyid_e
, "st_skeyid_e in generate_skeyids_iv()", &ctx
);
1266 union hash_ctx hash_ctx
;
1267 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1269 st
->st_new_iv_len
= h
->hash_digest_size
;
1270 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1273 DBG_dump_chunk("DH_i:", st
->st_gi
);
1274 DBG_dump_chunk("DH_r:", st
->st_gr
);
1276 h
->hash_init(&hash_ctx
);
1277 h
->hash_update(&hash_ctx
, st
->st_gi
.ptr
, st
->st_gi
.len
);
1278 h
->hash_update(&hash_ctx
, st
->st_gr
.ptr
, st
->st_gr
.len
);
1279 h
->hash_final(st
->st_new_iv
, &hash_ctx
);
1282 /* Oakley Keying Material
1283 * Derived from Skeyid_e: if it is not big enough, generate more
1285 * See RFC 2409 "IKE" Appendix B
1288 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1289 const size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1290 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1291 u_char
*k
= st
->st_skeyid_e
.ptr
;
1293 if (keysize
> st
->st_skeyid_e
.len
)
1295 struct hmac_ctx ctx
;
1298 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_e
);
1299 hmac_update(&ctx
, "\0", 1);
1302 hmac_final(&keytemp
[i
], &ctx
);
1303 i
+= ctx
.hmac_digest_size
;
1307 hmac_update(&ctx
, &keytemp
[i
- ctx
.hmac_digest_size
], ctx
.hmac_digest_size
);
1311 clonereplacechunk(st
->st_enc_key
, k
, keysize
, "st_enc_key");
1315 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1316 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1317 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1318 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1319 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1320 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1324 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1325 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1326 * New Group Mode, or ISAKMP Informational Exchanges).
1327 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1328 * If hashus argument is TRUE, we're generating a hash for our end.
1329 * See RFC2409 IKE 5.
1331 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1332 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1333 * The extensive common logic is embodied in main_mode_hash_body().
1334 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1337 typedef void (*hash_update_t
)(union hash_ctx
*, const u_char
*, size_t) ;
1339 main_mode_hash_body(struct state
*st
1340 , bool hashi
/* Initiator? */
1341 , const pb_stream
*idpl
/* ID payload, as PBS */
1342 , union hash_ctx
*ctx
1343 , void (*hash_update_void
)(void *, const u_char
*input
, size_t))
1345 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1346 hash_update_t hash_update
=(hash_update_t
) hash_update_void
;
1347 #if 0 /* if desperate to debug hashing */
1348 # define hash_update(ctx, input, len) { \
1349 DBG_dump("hash input", input, len); \
1350 (hash_update)(ctx, input, len); \
1354 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1358 hash_update_chunk(ctx
, st
->st_gi
);
1359 hash_update_chunk(ctx
, st
->st_gr
);
1360 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1361 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1365 hash_update_chunk(ctx
, st
->st_gr
);
1366 hash_update_chunk(ctx
, st
->st_gi
);
1367 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1368 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1371 DBG(DBG_CRYPT
, DBG_log("hashing %lu bytes of SA"
1372 , (unsigned long) (st
->st_p1isa
.len
- sizeof(struct isakmp_generic
))));
1375 hash_update(ctx
, st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
)
1376 , st
->st_p1isa
.len
- sizeof(struct isakmp_generic
));
1378 /* Hash identification payload, without generic payload header.
1379 * We used to reconstruct ID Payload for this purpose, but now
1380 * we use the bytes as they appear on the wire to avoid
1381 * "spelling problems".
1384 , idpl
->start
+ sizeof(struct isakmp_generic
)
1385 , pbs_offset(idpl
) - sizeof(struct isakmp_generic
));
1387 # undef hash_update_chunk
1391 static size_t /* length of hash */
1392 main_mode_hash(struct state
*st
1393 , u_char
*hash_val
/* resulting bytes */
1394 , bool hashi
/* Initiator? */
1395 , const pb_stream
*idpl
) /* ID payload, as PBS; cur must be at end */
1397 struct hmac_ctx ctx
;
1399 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1400 main_mode_hash_body(st
, hashi
, idpl
, &ctx
.hash_ctx
, ctx
.h
->hash_update
);
1401 hmac_final(hash_val
, &ctx
);
1402 return ctx
.hmac_digest_size
;
1405 #if 0 /* only needed for DSS */
1407 main_mode_sha1(struct state
*st
1408 , u_char
*hash_val
/* resulting bytes */
1409 , size_t *hash_len
/* length of hash */
1410 , bool hashi
/* Initiator? */
1411 , const pb_stream
*idpl
) /* ID payload, as PBS */
1415 SHA1Init(&ctx
.ctx_sha1
);
1416 SHA1Update(&ctx
.ctx_sha1
, st
->st_skeyid
.ptr
, st
->st_skeyid
.len
);
1417 *hash_len
= SHA1_DIGEST_SIZE
;
1418 main_mode_hash_body(st
, hashi
, idpl
, &ctx
1419 , (void (*)(union hash_ctx
*, const u_char
*, unsigned int))&SHA1Update
);
1420 SHA1Final(hash_val
, &ctx
.ctx_sha1
);
1424 /* Create an RSA signature of a hash.
1425 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1426 * Use PKCS#1 version 1.5 encryption of hash (called
1427 * RSAES-PKCS1-V1_5) in PKCS#2.
1430 RSA_sign_hash(struct connection
*c
1431 , u_char sig_val
[RSA_MAX_OCTETS
]
1432 , const u_char
*hash_val
, size_t hash_len
)
1435 smartcard_t
*sc
= c
->spd
.this.sc
;
1437 if (sc
== NULL
) /* no smartcard */
1439 const struct RSA_private_key
*k
= get_RSA_private_key(c
);
1442 return 0; /* failure: no key to use */
1445 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1446 sign_hash(k
, hash_val
, hash_len
, sig_val
, sz
);
1448 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1450 lock_certs_and_keys("RSA_sign_hash");
1451 if (!scx_establish_context(sc
) || !scx_login(sc
))
1453 scx_release_context(sc
);
1454 unlock_certs_and_keys("RSA_sign_hash");
1458 sz
= scx_get_keylength(sc
);
1461 plog("failed to get keylength from smartcard");
1462 scx_release_context(sc
);
1463 unlock_certs_and_keys("RSA_sign_hash");
1467 DBG(DBG_CONTROL
| DBG_CRYPT
,
1468 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1469 , (int)sc
->slot
, sc
->id
)
1471 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1472 if (!pkcs11_keep_state
)
1473 scx_release_context(sc
);
1474 unlock_certs_and_keys("RSA_sign_hash");
1479 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1481 * As a side effect, on success, the public key is copied into the
1482 * state object to record the authenticator.
1484 * Can fail because wrong public key is used or because hash disagrees.
1485 * We distinguish because diagnostics should also.
1487 * The result is NULL if the Signature checked out.
1488 * Otherwise, the first character of the result indicates
1489 * how far along failure occurred. A greater character signifies
1493 * 0 reserved for caller
1494 * 1 SIG length doesn't match key length -- wrong key
1495 * 2-8 malformed ECB after decryption -- probably wrong key
1496 * 9 decrypted hash != computed hash -- probably correct key
1498 * Although the math should be the same for generating and checking signatures,
1499 * it is not: the knowledge of the private key allows more efficient (i.e.
1500 * different) computation for encryption.
1503 try_RSA_signature(const u_char hash_val
[MAX_DIGEST_LEN
], size_t hash_len
1504 , const pb_stream
*sig_pbs
, pubkey_t
*kr
1507 const u_char
*sig_val
= sig_pbs
->cur
;
1508 size_t sig_len
= pbs_left(sig_pbs
);
1509 u_char s
[RSA_MAX_OCTETS
]; /* for decrypted sig_val */
1510 u_char
*hash_in_s
= &s
[sig_len
- hash_len
];
1511 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1513 /* decrypt the signature -- reversing RSA_sign_hash */
1514 if (sig_len
!= k
->k
)
1516 /* XXX notification: INVALID_KEY_INFORMATION */
1517 return "1" "SIG length does not match public key length";
1520 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1525 n_to_mpz(c
, sig_val
, sig_len
);
1526 mpz_powm(c
, c
, &k
->e
, &k
->n
);
1528 temp_s
= mpz_to_n(c
, sig_len
); /* back to octets */
1529 memcpy(s
, temp_s
.ptr
, sig_len
);
1534 /* sanity check on signature: see if it matches
1535 * PKCS#1 v1.5 8.1 encryption-block formatting
1541 ugh
= "2" "no leading 00";
1542 else if (hash_in_s
[-1] != 0x00)
1543 ugh
= "3" "00 separator not present";
1544 else if (s
[1] == 0x01)
1548 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1552 ugh
= "4" "invalid Padding String";
1557 else if (s
[1] == 0x02)
1561 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1565 ugh
= "5" "invalid Padding String";
1571 ugh
= "6" "Block Type not 01 or 02";
1575 /* note: it might be a good idea to make sure that
1576 * an observer cannot tell what kind of failure happened.
1577 * I don't know what this means in practice.
1579 /* We probably selected the wrong public key for peer:
1580 * SIG Payload decrypted into malformed ECB
1582 /* XXX notification: INVALID_KEY_INFORMATION */
1587 /* We have the decoded hash: see if it matches. */
1588 if (memcmp(hash_val
, hash_in_s
, hash_len
) != 0)
1590 /* good: header, hash, signature, and other payloads well-formed
1591 * good: we could find an RSA Sig key for the peer.
1592 * bad: hash doesn't match
1593 * Guess: sides disagree about key to be used.
1595 DBG_cond_dump(DBG_CRYPT
, "decrypted SIG", s
, sig_len
);
1596 DBG_cond_dump(DBG_CRYPT
, "computed HASH", hash_val
, hash_len
);
1597 /* XXX notification: INVALID_HASH_INFORMATION */
1598 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1601 /* Success: copy successful key into state.
1602 * There might be an old one if we previously aborted this
1605 unreference_key(&st
->st_peer_pubkey
);
1606 st
->st_peer_pubkey
= reference_key(kr
);
1608 return NULL
; /* happy happy */
1611 /* Check signature against all RSA public keys we can find.
1612 * If we need keys from DNS KEY records, and they haven't been fetched,
1613 * return STF_SUSPEND to ask for asynch DNS lookup.
1615 * Note: parameter keys_from_dns contains results of DNS lookup for key
1616 * or is NULL indicating lookup not yet tried.
1618 * take_a_crack is a helper function. Mostly forensic.
1619 * If only we had coroutines.
1622 /* RSA_check_signature's args that take_a_crack needs */
1624 const u_char
*hash_val
;
1626 const pb_stream
*sig_pbs
;
1628 /* state carried between calls */
1629 err_t best_ugh
; /* most successful failure */
1630 int tried_cnt
; /* number of keys tried */
1631 char tried
[50]; /* keyids of tried public keys */
1632 char *tn
; /* roof of tried[] */
1636 take_a_crack(struct tac_state
*s
1638 , const char *story USED_BY_DEBUG
)
1640 err_t ugh
= try_RSA_signature(s
->hash_val
, s
->hash_len
, s
->sig_pbs
1642 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1647 DBG(DBG_CRYPT
| DBG_CONTROL
1648 , DBG_log("an RSA Sig check passed with *%s [%s]"
1649 , k
->keyid
, story
));
1655 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1656 , ugh
+ 1, k
->keyid
, story
));
1657 if (s
->best_ugh
== NULL
|| s
->best_ugh
[0] < ugh
[0])
1660 && s
->tn
- s
->tried
+ KEYID_BUF
+ 2 < (ptrdiff_t)sizeof(s
->tried
))
1662 strcpy(s
->tn
, " *");
1663 strcpy(s
->tn
+ 2, k
->keyid
);
1664 s
->tn
+= strlen(s
->tn
);
1671 RSA_check_signature(const struct id
* peer
1673 , const u_char hash_val
[MAX_DIGEST_LEN
]
1675 , const pb_stream
*sig_pbs
1677 , const pubkey_list_t
*keys_from_dns
1678 #endif /* USE_KEYRR */
1679 , const struct gw_info
*gateways_from_dns
1682 const struct connection
*c
= st
->st_connection
;
1684 err_t dns_ugh
= NULL
;
1687 s
.hash_val
= hash_val
;
1688 s
.hash_len
= hash_len
;
1689 s
.sig_pbs
= sig_pbs
;
1695 /* try all gateway records hung off c */
1696 if (c
->policy
& POLICY_OPPO
)
1700 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1702 /* only consider entries that have a key and are for our peer */
1703 if (gw
->gw_key_present
1704 && same_id(&gw
->gw_id
, &c
->spd
.that
.id
)
1705 && take_a_crack(&s
, gw
->key
, "key saved from DNS TXT"))
1710 /* try all appropriate Public keys */
1712 pubkey_list_t
*p
, **pp
;
1716 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1718 pubkey_t
*key
= p
->key
;
1720 if (key
->alg
== PUBKEY_ALG_RSA
&& same_id(peer
, &key
->id
))
1722 time_t now
= time(NULL
);
1724 /* check if found public key has expired */
1725 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1727 loglog(RC_LOG_SERIOUS
,
1728 "cached RSA public key has expired and has been deleted");
1729 *pp
= free_public_keyentry(p
);
1730 continue; /* continue with next public key */
1733 if (take_a_crack(&s
, key
, "preloaded key"))
1740 /* if no key was found (evidenced by best_ugh == NULL)
1741 * and that side of connection is key_from_DNS_on_demand
1742 * then go search DNS for keys for peer.
1744 if (s
.best_ugh
== NULL
&& c
->spd
.that
.key_from_DNS_on_demand
)
1746 if (gateways_from_dns
!= NULL
)
1749 const struct gw_info
*gwp
;
1751 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1752 if (gwp
->gw_key_present
1753 && take_a_crack(&s
, gwp
->key
, "key from DNS TXT"))
1757 else if (keys_from_dns
!= NULL
)
1760 const pubkey_list_t
*kr
;
1762 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1763 if (kr
->key
->alg
== PUBKEY_ALG_RSA
1764 && take_a_crack(&s
, kr
->key
, "key from DNS KEY"))
1767 #endif /* USE_KEYRR */
1770 /* nothing yet: ask for asynch DNS lookup */
1775 /* no acceptable key was found: diagnose */
1777 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1779 (void) idtoa(peer
, id_buf
, sizeof(id_buf
));
1781 if (s
.best_ugh
== NULL
)
1783 if (dns_ugh
== NULL
)
1784 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1787 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1788 "; DNS search for KEY failed (%s)"
1791 /* ??? is this the best code there is? */
1792 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1795 if (s
.best_ugh
[0] == '9')
1797 loglog(RC_LOG_SERIOUS
, "%s", s
.best_ugh
+ 1);
1798 /* XXX Could send notification back */
1799 return STF_FAIL
+ INVALID_HASH_INFORMATION
;
1803 if (s
.tried_cnt
== 1)
1805 loglog(RC_LOG_SERIOUS
1806 , "Signature check (on %s) failed (wrong key?); tried%s"
1809 DBG_log("public key for %s failed:"
1810 " decrypted SIG payload into a malformed ECB (%s)"
1811 , id_buf
, s
.best_ugh
+ 1));
1815 loglog(RC_LOG_SERIOUS
1816 , "Signature check (on %s) failed:"
1817 " tried%s keys but none worked."
1820 DBG_log("all %d public keys for %s failed:"
1821 " best decrypted SIG payload into a malformed ECB (%s)"
1822 , s
.tried_cnt
, id_buf
, s
.best_ugh
+ 1));
1824 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1829 static notification_t
1830 accept_nonce(struct msg_digest
*md
, chunk_t
*dest
, const char *name
)
1832 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1833 size_t len
= pbs_left(nonce_pbs
);
1835 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1837 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1838 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1839 return PAYLOAD_MALFORMED
; /* ??? */
1841 clonereplacechunk(*dest
, nonce_pbs
->cur
, len
, "nonce");
1842 return NOTHING_WRONG
;
1845 /* encrypt message, sans fixed part of header
1846 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1847 * The theory is that there will be no "backing out", so we commit to IV.
1848 * We also close the pbs.
1851 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1853 const struct encrypt_desc
*e
= st
->st_oakley
.encrypter
;
1854 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1855 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1857 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1859 /* Pad up to multiple of encryption blocksize.
1860 * See the description associated with the definition of
1861 * struct isakmp_hdr in packet.h.
1864 size_t padding
= pad_up(enc_len
, e
->enc_blocksize
);
1868 if (!out_zero(padding
, pbs
, "encryption padding"))
1874 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1876 /* e->crypt(TRUE, enc_start, enc_len, st); */
1877 crypto_cbc_encrypt(e
, TRUE
, enc_start
, enc_len
, st
);
1880 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1885 /* Compute HASH(1), HASH(2) of Quick Mode.
1886 * HASH(1) is part of Quick I1 message.
1887 * HASH(2) is part of Quick R1 message.
1888 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1889 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1892 quick_mode_hash12(u_char
*dest
, const u_char
*start
, const u_char
*roof
1893 , const struct state
*st
, const msgid_t
*msgid
, bool hash2
)
1895 struct hmac_ctx ctx
;
1897 #if 0 /* if desperate to debug hashing */
1898 # define hmac_update(ctx, ptr, len) { \
1899 DBG_dump("hash input", (ptr), (len)); \
1900 (hmac_update)((ctx), (ptr), (len)); \
1902 DBG_dump("hash key", st
->st_skeyid_a
.ptr
, st
->st_skeyid_a
.len
);
1904 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1905 hmac_update(&ctx
, (const void *) msgid
, sizeof(msgid_t
));
1907 hmac_update_chunk(&ctx
, st
->st_ni
); /* include Ni_b in the hash */
1908 hmac_update(&ctx
, start
, roof
-start
);
1909 hmac_final(dest
, &ctx
);
1912 DBG_log("HASH(%d) computed:", hash2
+ 1);
1913 DBG_dump("", dest
, ctx
.hmac_digest_size
));
1914 return ctx
.hmac_digest_size
;
1918 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1919 * Used by: quick_inR1_outI2, quick_inI2
1920 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1921 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1922 * Message ID and Nonces. This is a mistake.
1925 quick_mode_hash3(u_char
*dest
, struct state
*st
)
1927 struct hmac_ctx ctx
;
1929 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1930 hmac_update(&ctx
, "\0", 1);
1931 hmac_update(&ctx
, (u_char
*) &st
->st_msgid
, sizeof(st
->st_msgid
));
1932 hmac_update_chunk(&ctx
, st
->st_ni
);
1933 hmac_update_chunk(&ctx
, st
->st_nr
);
1934 hmac_final(dest
, &ctx
);
1935 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, ctx
.hmac_digest_size
);
1936 return ctx
.hmac_digest_size
;
1939 /* Compute Phase 2 IV.
1940 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1943 init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1945 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1948 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:"
1949 , st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1951 st
->st_new_iv_len
= h
->hash_digest_size
;
1952 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1955 h
->hash_update(&ctx
, st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1956 passert(*msgid
!= 0);
1957 h
->hash_update(&ctx
, (const u_char
*)msgid
, sizeof(*msgid
));
1958 h
->hash_final(st
->st_new_iv
, &ctx
);
1960 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:"
1961 , st
->st_new_iv
, st
->st_new_iv_len
);
1964 /* Initiate quick mode.
1965 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1966 * (see RFC 2409 "IKE" 5.5)
1967 * Note: this is not called from demux.c
1971 emit_subnet_id(ip_subnet
*net
1972 , u_int8_t np
, u_int8_t protoid
, u_int16_t port
, pb_stream
*outs
)
1974 struct isakmp_ipsec_id id
;
1977 const unsigned char *tbp
;
1981 id
.isaiid_idtype
= subnetishost(net
)
1982 ?
aftoinfo(subnettypeof(net
))->id_addr
1983 : aftoinfo(subnettypeof(net
))->id_subnet
;
1984 id
.isaiid_protoid
= protoid
;
1985 id
.isaiid_port
= port
;
1987 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
1990 networkof(net
, &ta
);
1991 tal
= addrbytesptr(&ta
, &tbp
);
1992 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
1995 if (!subnetishost(net
))
1998 tal
= addrbytesptr(&ta
, &tbp
);
1999 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
2003 close_output_pbs(&id_pbs
);
2008 quick_outI1(int whack_sock
2009 , struct state
*isakmp_sa
2010 , struct connection
*c
2013 , so_serial_t replacing
)
2015 struct state
*st
= duplicate_state(isakmp_sa
);
2016 pb_stream reply
; /* not really a reply */
2018 u_char
/* set by START_HASH_PAYLOAD: */
2019 *r_hashval
, /* where in reply to jam hash value */
2020 *r_hash_start
; /* start of what is to be hashed */
2021 bool has_client
= c
->spd
.this.has_client
|| c
->spd
.that
.has_client
||
2022 c
->spd
.this.protocol
|| c
->spd
.that
.protocol
||
2023 c
->spd
.this.port
|| c
->spd
.that
.port
;
2025 bool send_natoa
= FALSE
;
2026 u_int8_t np
= ISAKMP_NEXT_NONE
;
2028 st
->st_whack_sock
= whack_sock
;
2029 st
->st_connection
= c
;
2030 set_cur_state(st
); /* we must reset before exit */
2031 st
->st_policy
= policy
;
2034 st
->st_myuserprotoid
= c
->spd
.this.protocol
;
2035 st
->st_peeruserprotoid
= c
->spd
.that
.protocol
;
2036 st
->st_myuserport
= c
->spd
.this.port
;
2037 st
->st_peeruserport
= c
->spd
.that
.port
;
2039 st
->st_msgid
= generate_msgid(isakmp_sa
);
2040 st
->st_state
= STATE_QUICK_I1
;
2042 insert_state(st
); /* needs cookies, connection, and msgid */
2044 if (replacing
== SOS_NOBODY
)
2045 plog("initiating Quick Mode %s {using isakmp#%lu}"
2046 , prettypolicy(policy
)
2047 , isakmp_sa
->st_serialno
);
2049 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2050 , prettypolicy(policy
)
2052 , isakmp_sa
->st_serialno
);
2054 if (isakmp_sa
->nat_traversal
& NAT_T_DETECTED
)
2056 /* Duplicate nat_traversal status in new state */
2057 st
->nat_traversal
= isakmp_sa
->nat_traversal
;
2059 if (isakmp_sa
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
))
2062 nat_traversal_change_port_lookup(NULL
, st
);
2065 st
->nat_traversal
= 0;
2067 /* are we going to send a NAT-OA payload? */
2068 if ((st
->nat_traversal
& NAT_T_WITH_NATOA
)
2069 && !(st
->st_policy
& POLICY_TUNNEL
)
2070 && (st
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
)))
2073 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
2074 ISAKMP_NEXT_NATOA_RFC
: ISAKMP_NEXT_NATOA_DRAFTS
;
2078 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
2082 struct isakmp_hdr hdr
;
2084 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
2085 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
2086 hdr
.isa_xchg
= ISAKMP_XCHG_QUICK
;
2087 hdr
.isa_msgid
= st
->st_msgid
;
2088 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
2089 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
2090 memcpy(hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
2091 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
2094 return STF_INTERNAL_ERROR
;
2098 /* HASH(1) -- create and note space to be filled later */
2099 START_HASH_PAYLOAD(rbody
, ISAKMP_NEXT_SA
);
2104 * See if pfs_group has been specified for this conn,
2105 * if not, fallback to old use-same-as-P1 behaviour
2108 if (st
->st_connection
)
2109 st
->st_pfs_group
= ike_alg_pfsgroup(st
->st_connection
, policy
);
2110 if (!st
->st_pfs_group
)
2112 /* If PFS specified, use the same group as during Phase 1:
2113 * since no negotiation is possible, we pick one that is
2114 * very likely supported.
2116 st
->st_pfs_group
= policy
& POLICY_PFS? isakmp_sa
->st_oakley
.group
: NULL
;
2118 /* Emit SA payload based on a subset of the policy bits.
2119 * POLICY_COMPRESS is considered iff we can do IPcomp.
2122 lset_t pm
= POLICY_ENCRYPT
| POLICY_AUTHENTICATE
;
2125 pm
|= POLICY_COMPRESS
;
2128 , &ipsec_sadb
[(st
->st_policy
& pm
) >> POLICY_IPSEC_SHIFT
]
2129 , st
, FALSE
, ISAKMP_NEXT_NONCE
))
2132 return STF_INTERNAL_ERROR
;
2137 if (!build_and_ship_nonce(&st
->st_ni
, &rbody
2138 , policy
& POLICY_PFS? ISAKMP_NEXT_KE
: has_client? ISAKMP_NEXT_ID
: np
2142 return STF_INTERNAL_ERROR
;
2145 /* [ KE ] out (for PFS) */
2147 if (st
->st_pfs_group
!= NULL
)
2149 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_pfs_group
2150 , &rbody
, has_client? ISAKMP_NEXT_ID
: np
))
2153 return STF_INTERNAL_ERROR
;
2157 /* [ IDci, IDcr ] out */
2160 /* IDci (we are initiator), then IDcr (peer is responder) */
2161 if (!emit_subnet_id(&c
->spd
.this.client
2162 , ISAKMP_NEXT_ID
, st
->st_myuserprotoid
, st
->st_myuserport
, &rbody
)
2163 || !emit_subnet_id(&c
->spd
.that
.client
2164 , np
, st
->st_peeruserprotoid
, st
->st_peeruserport
, &rbody
))
2167 return STF_INTERNAL_ERROR
;
2171 /* Send NAT-OA if our address is NATed */
2174 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE
, &rbody
, st
))
2177 return STF_INTERNAL_ERROR
;
2181 /* finish computing HASH(1), inserting it in output */
2182 (void) quick_mode_hash12(r_hashval
, r_hash_start
, rbody
.cur
2183 , st
, &st
->st_msgid
, FALSE
);
2185 /* encrypt message, except for fixed part of header */
2187 init_phase2_iv(isakmp_sa
, &st
->st_msgid
);
2188 st
->st_new_iv_len
= isakmp_sa
->st_new_iv_len
;
2189 memcpy(st
->st_new_iv
, isakmp_sa
->st_new_iv
, st
->st_new_iv_len
);
2191 if (!encrypt_message(&rbody
, st
))
2194 return STF_INTERNAL_ERROR
;
2197 /* save packet, now that we know its size */
2198 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
2199 , "reply packet from quick_outI1");
2201 /* send the packet */
2203 send_packet(st
, "quick_outI1");
2206 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
2208 if (replacing
== SOS_NOBODY
)
2209 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2211 , enum_name(&state_names
, st
->st_state
));
2213 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2214 , "%s: initiate to replace #%lu"
2215 , enum_name(&state_names
, st
->st_state
)
2223 * Decode the CERT payload of Phase 1.
2226 decode_cert(struct msg_digest
*md
)
2228 struct payload_digest
*p
;
2230 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2232 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2235 blob
.ptr
= p
->pbs
.cur
;
2236 blob
.len
= pbs_left(&p
->pbs
);
2237 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2239 x509cert_t cert
= empty_x509cert
;
2240 if (parse_x509cert(blob
, 0, &cert
))
2242 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2245 DBG_log("Public key validated")
2247 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2251 plog("X.509 certificate rejected");
2253 free_generalNames(cert
.subjectAltName
, FALSE
);
2254 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2257 plog("Syntax error in X.509 certificate");
2259 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2261 x509cert_t
*cert
= NULL
;
2263 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2264 store_x509certs(&cert
, strict_crl_policy
);
2266 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2270 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2271 enum_show(&cert_type_names
, cert
->isacert_type
));
2272 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2278 * Decode the CR payload of Phase 1.
2281 decode_cr(struct msg_digest
*md
, struct connection
*c
)
2283 struct payload_digest
*p
;
2285 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2287 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2290 ca_name
.len
= pbs_left(&p
->pbs
);
2291 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2293 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2295 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2299 if (ca_name
.len
> 0)
2303 if (!is_asn1(ca_name
))
2306 gn
= alloc_thing(generalName_t
, "generalName");
2307 clonetochunk(ca_name
, ca_name
.ptr
,ca_name
.len
, "ca name");
2308 gn
->kind
= GN_DIRECTORY_NAME
;
2310 gn
->next
= c
->requested_ca
;
2311 c
->requested_ca
= gn
;
2313 c
->got_certrequest
= TRUE
;
2315 DBG(DBG_PARSING
| DBG_CONTROL
,
2316 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2317 DBG_log("requested CA: '%s'", buf
);
2321 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2322 enum_show(&cert_type_names
, cr
->isacr_type
));
2326 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2327 * Note: we may change connections as a result.
2328 * We must be called before SIG or HASH are decoded since we
2329 * may change the peer's RSA key or ID.
2332 decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2334 struct state
*const st
= md
->st
;
2335 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2336 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2337 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2339 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2340 * It talks about the protocol ID and Port fields of the ID
2341 * Payload, but they don't exist as such in Phase 1.
2342 * We use more appropriate names.
2343 * isaid_doi_specific_a is in place of Protocol ID.
2344 * isaid_doi_specific_b is in place of Port.
2345 * Besides, there is no good reason for allowing these to be
2346 * other than 0 in Phase 1.
2348 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2349 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2350 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2352 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2353 "accepted with port_floating NAT-T",
2354 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2356 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2357 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2359 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2361 , IPPROTO_UDP
, IKE_UDP_PORT
2362 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2366 peer
->kind
= id
->isaid_idtype
;
2372 /* failure mode for initaddr is probably inappropriate address length */
2374 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2375 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2380 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2381 , enum_show(&ident_names
, peer
->kind
), ugh
);
2382 /* XXX Could send notification back */
2389 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2391 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2396 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2398 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2399 , enum_show(&ident_names
, peer
->kind
));
2403 /* ??? ought to do some more sanity check, but what? */
2405 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2409 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2411 DBG_dump_chunk("KEY ID:", peer
->name
));
2414 case ID_DER_ASN1_DN
:
2415 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2417 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2421 /* XXX Could send notification back */
2422 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2423 , enum_show(&ident_names
, peer
->kind
));
2430 idtoa(peer
, buf
, sizeof(buf
));
2431 plog("Peer ID is %s: '%s'",
2432 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2435 /* check for certificates */
2440 /* Now that we've decoded the ID payload, let's see if we
2441 * need to switch connections.
2442 * We must not switch horses if we initiated:
2443 * - if the initiation was explicit, we'd be ignoring user's intent
2444 * - if opportunistic, we'll lose our HOLD info
2447 switch_connection(struct msg_digest
*md
, struct id
*peer
, bool initiator
)
2449 struct state
*const st
= md
->st
;
2450 struct connection
*c
= st
->st_connection
;
2452 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2453 ? st
->st_peer_pubkey
->issuer
: empty_chunk
;
2458 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2459 DBG_log("peer CA: '%s'", buf
);
2466 if (!same_id(&c
->spd
.that
.id
, peer
))
2468 char expect
[BUF_LEN
]
2471 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2472 idtoa(peer
, found
, sizeof(found
));
2473 loglog(RC_LOG_SERIOUS
2474 , "we require peer to have ID '%s', but peer declares '%s'"
2482 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.that
.ca
, "%none");
2483 DBG_log("required CA: '%s'", buf
);
2486 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2488 loglog(RC_LOG_SERIOUS
2489 , "we don't accept the peer's CA");
2495 struct connection
*r
;
2497 /* check for certificate requests */
2500 r
= refine_host_connection(st
, peer
, peer_ca
);
2502 /* delete the collected certificate requests */
2503 free_generalNames(c
->requested_ca
, TRUE
);
2504 c
->requested_ca
= NULL
;
2510 idtoa(peer
, buf
, sizeof(buf
));
2511 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2518 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2519 DBG_log("offered CA: '%s'", buf
);
2524 /* apparently, r is an improvement on c -- replace */
2527 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2528 if (r
->kind
== CK_TEMPLATE
)
2530 /* instantiate it, filling in peer's ID */
2531 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2532 , c
->spd
.that
.host_port
, NULL
, peer
);
2535 /* copy certificate request info */
2536 r
->got_certrequest
= c
->got_certrequest
;
2538 st
->st_connection
= r
; /* kill reference to c */
2539 set_cur_connection(r
);
2540 connection_discard(c
);
2542 else if (c
->spd
.that
.has_id_wildcards
)
2544 free_id_content(&c
->spd
.that
.id
);
2545 c
->spd
.that
.id
= *peer
;
2546 c
->spd
.that
.has_id_wildcards
= FALSE
;
2547 unshare_id_content(&c
->spd
.that
.id
);
2553 /* Decode the variable part of an ID packet (during Quick Mode).
2554 * This is designed for packets that identify clients, not peers.
2555 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2556 * (1) it is wrong and (2) we use this value for inband signalling.
2559 decode_net_id(struct isakmp_ipsec_id
*id
2562 , const char *which
)
2564 const struct af_info
*afi
= NULL
;
2566 /* Note: the following may be a pointer into static memory
2567 * that may be recycled, but only if the type is not known.
2568 * That case is disposed of very early -- in the first switch.
2570 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2572 switch (id
->isaiid_idtype
)
2575 case ID_IPV4_ADDR_SUBNET
:
2576 case ID_IPV4_ADDR_RANGE
:
2577 afi
= &af_inet4_info
;
2580 case ID_IPV6_ADDR_SUBNET
:
2581 case ID_IPV6_ADDR_RANGE
:
2582 afi
= &af_inet6_info
;
2587 /* XXX support more */
2588 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2590 /* XXX Could send notification back */
2594 switch (id
->isaiid_idtype
)
2599 ip_address temp_address
;
2602 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2606 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2607 , which
, idtypename
, ugh
);
2608 /* XXX Could send notification back */
2611 if (isanyaddr(&temp_address
))
2613 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2614 , which
, idtypename
, ip_str(&temp_address
));
2615 /* XXX Could send notification back */
2618 happy(addrtosubnet(&temp_address
, net
));
2619 DBG(DBG_PARSING
| DBG_CONTROL
2620 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2624 case ID_IPV4_ADDR_SUBNET
:
2625 case ID_IPV6_ADDR_SUBNET
:
2627 ip_address temp_address
, temp_mask
;
2630 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2632 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2633 , which
, idtypename
);
2634 /* XXX Could send notification back */
2637 ugh
= initaddr(id_pbs
->cur
2638 , afi
->ia_sz
, afi
->af
, &temp_address
);
2640 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2641 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2643 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2645 if (ugh
== NULL
&& subnetisnone(net
))
2646 ugh
= "contains only anyaddr";
2649 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2650 , which
, idtypename
, ugh
);
2651 /* XXX Could send notification back */
2654 DBG(DBG_PARSING
| DBG_CONTROL
,
2656 char temp_buff
[SUBNETTOT_BUF
];
2658 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2659 DBG_log("%s is subnet %s", which
, temp_buff
);
2664 case ID_IPV4_ADDR_RANGE
:
2665 case ID_IPV6_ADDR_RANGE
:
2667 ip_address temp_address_from
, temp_address_to
;
2670 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2672 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2673 , which
, idtypename
);
2674 /* XXX Could send notification back */
2677 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2679 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2680 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2683 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2684 , which
, idtypename
, ugh
);
2685 /* XXX Could send notification back */
2689 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2690 if (ugh
== NULL
&& subnetisnone(net
))
2691 ugh
= "contains only anyaddr";
2694 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2696 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2697 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2698 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2699 " %s - %s unacceptable: %s"
2700 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2703 DBG(DBG_PARSING
| DBG_CONTROL
,
2705 char temp_buff
[SUBNETTOT_BUF
];
2707 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2708 DBG_log("%s is subnet %s (received as range)"
2709 , which
, temp_buff
);
2715 /* set the port selector */
2716 setportof(htons(id
->isaiid_port
), &net
->addr
);
2718 DBG(DBG_PARSING
| DBG_CONTROL
,
2719 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2725 /* like decode, but checks that what is received matches what was sent */
2728 check_net_id(struct isakmp_ipsec_id
*id
2733 , const char *which
)
2737 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2740 if (!samesubnet(net
, &net_temp
)
2741 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2743 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2750 * look for the existence of a non-expiring preloaded public key
2753 has_preloaded_public_key(struct state
*st
)
2755 struct connection
*c
= st
->st_connection
;
2757 /* do not consider rw connections since
2758 * the peer's identity must be known
2760 if (c
->kind
== CK_PERMANENT
)
2764 /* look for a matching RSA public key */
2765 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2767 pubkey_t
*key
= p
->key
;
2769 if (key
->alg
== PUBKEY_ALG_RSA
&&
2770 same_id(&c
->spd
.that
.id
, &key
->id
) &&
2771 key
->until_time
== UNDEFINED_TIME
)
2773 /* found a preloaded public key */
2782 * Produce the new key material of Quick Mode.
2783 * RFC 2409 "IKE" section 5.5
2784 * specifies how this is to be done.
2787 compute_proto_keymat(struct state
*st
2789 , struct ipsec_proto_info
*pi
)
2791 size_t needed_len
; /* bytes of keying material needed */
2793 /* Add up the requirements for keying material
2794 * (It probably doesn't matter if we produce too much!)
2798 case PROTO_IPSEC_ESP
:
2799 switch (pi
->attrs
.transid
)
2805 needed_len
= DES_CBC_BLOCK_SIZE
;
2808 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2811 #ifndef NO_KERNEL_ALG
2812 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2813 /* XXX: check key_len "coupling with kernel.c's */
2814 if (pi
->attrs
.key_len
) {
2815 needed_len
=pi
->attrs
.key_len
/8;
2816 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2817 "key_len=%d from peer",
2823 bad_case(pi
->attrs
.transid
);
2826 #ifndef NO_KERNEL_ALG
2827 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2828 "needed_len (after ESP enc)=%d",
2830 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2831 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2834 switch (pi
->attrs
.auth
)
2836 case AUTH_ALGORITHM_NONE
:
2838 case AUTH_ALGORITHM_HMAC_MD5
:
2839 needed_len
+= HMAC_MD5_KEY_LEN
;
2841 case AUTH_ALGORITHM_HMAC_SHA1
:
2842 needed_len
+= HMAC_SHA1_KEY_LEN
;
2844 case AUTH_ALGORITHM_DES_MAC
:
2846 bad_case(pi
->attrs
.auth
);
2848 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2849 "needed_len (after ESP auth)=%d",
2853 case PROTO_IPSEC_AH
:
2854 switch (pi
->attrs
.transid
)
2857 needed_len
= HMAC_MD5_KEY_LEN
;
2860 needed_len
= HMAC_SHA1_KEY_LEN
;
2863 bad_case(pi
->attrs
.transid
);
2871 pi
->keymat_len
= needed_len
;
2873 /* Allocate space for the keying material.
2874 * Although only needed_len bytes are desired, we
2875 * must round up to a multiple of ctx.hmac_digest_size
2876 * so that our buffer isn't overrun.
2879 struct hmac_ctx ctx_me
, ctx_peer
;
2880 size_t needed_space
; /* space needed for keying material (rounded up) */
2883 hmac_init_chunk(&ctx_me
, st
->st_oakley
.hasher
, st
->st_skeyid_d
);
2884 ctx_peer
= ctx_me
; /* duplicate initial conditions */
2886 needed_space
= needed_len
+ pad_up(needed_len
, ctx_me
.hmac_digest_size
);
2887 replace(pi
->our_keymat
, alloc_bytes(needed_space
, "keymat in compute_keymat()"));
2888 replace(pi
->peer_keymat
, alloc_bytes(needed_space
, "peer_keymat in quick_inI1_outR1()"));
2892 if (st
->st_shared
.ptr
!= NULL
)
2894 /* PFS: include the g^xy */
2895 hmac_update_chunk(&ctx_me
, st
->st_shared
);
2896 hmac_update_chunk(&ctx_peer
, st
->st_shared
);
2898 hmac_update(&ctx_me
, &protoid
, sizeof(protoid
));
2899 hmac_update(&ctx_peer
, &protoid
, sizeof(protoid
));
2901 hmac_update(&ctx_me
, (u_char
*)&pi
->our_spi
, sizeof(pi
->our_spi
));
2902 hmac_update(&ctx_peer
, (u_char
*)&pi
->attrs
.spi
, sizeof(pi
->attrs
.spi
));
2904 hmac_update_chunk(&ctx_me
, st
->st_ni
);
2905 hmac_update_chunk(&ctx_peer
, st
->st_ni
);
2907 hmac_update_chunk(&ctx_me
, st
->st_nr
);
2908 hmac_update_chunk(&ctx_peer
, st
->st_nr
);
2910 hmac_final(pi
->our_keymat
+ i
, &ctx_me
);
2911 hmac_final(pi
->peer_keymat
+ i
, &ctx_peer
);
2913 i
+= ctx_me
.hmac_digest_size
;
2914 if (i
>= needed_space
)
2917 /* more keying material needed: prepare to go around again */
2919 hmac_reinit(&ctx_me
);
2920 hmac_reinit(&ctx_peer
);
2922 hmac_update(&ctx_me
, pi
->our_keymat
+ i
- ctx_me
.hmac_digest_size
2923 , ctx_me
.hmac_digest_size
);
2924 hmac_update(&ctx_peer
, pi
->peer_keymat
+ i
- ctx_peer
.hmac_digest_size
2925 , ctx_peer
.hmac_digest_size
);
2930 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2931 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2935 compute_keymats(struct state
*st
)
2937 if (st
->st_ah
.present
)
2938 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2939 if (st
->st_esp
.present
)
2940 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2943 /* State Transition Functions.
2945 * The definition of state_microcode_table in demux.c is a good
2946 * overview of these routines.
2948 * - Called from process_packet; result handled by complete_state_transition
2949 * - struct state_microcode member "processor" points to these
2950 * - these routine definitionss are in state order
2951 * - these routines must be restartable from any point of error return:
2952 * beware of memory allocated before any error.
2953 * - output HDR is usually emitted by process_packet (if state_microcode
2954 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2956 * The transition functions' functions include:
2957 * - process and judge payloads
2958 * - update st_iv (result of decryption is in st_new_iv)
2959 * - build reply packet
2962 /* Handle a Main Mode Oakley first packet (responder side).
2966 main_inI1_outR1(struct msg_digest
*md
)
2968 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2970 struct connection
*c
;
2971 struct isakmp_proposal proposal
;
2972 pb_stream proposal_pbs
;
2974 u_int32_t ipsecdoisit
;
2975 lset_t policy
= LEMPTY
;
2976 int vids_to_send
= 0;
2978 /* We preparse the peer's proposal in order to determine
2979 * the requested authentication policy (RSA or PSK)
2981 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2982 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2984 backup_pbs(&proposal_pbs
);
2985 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2986 , proposal
.isap_notrans
, &policy
));
2987 restore_pbs(&proposal_pbs
);
2989 /* We are only considering candidate connections that match
2990 * the requested authentication policy (RSA or PSK)
2992 c
= find_host_connection(&md
->iface
->addr
, pluto_port
2993 , &md
->sender
, md
->sender_port
, policy
);
2995 if (c
== NULL
&& md
->iface
->ike_float
)
2997 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
2998 , &md
->sender
, md
->sender_port
, policy
);
3003 /* See if a wildcarded connection can be found.
3004 * We cannot pick the right connection, so we're making a guess.
3005 * All Road Warrior connections are fair game:
3006 * we pick the first we come across (if any).
3007 * If we don't find any, we pick the first opportunistic
3008 * with the smallest subnet that includes the peer.
3009 * There is, of course, no necessary relationship between
3010 * an Initiator's address and that of its client,
3011 * but Food Groups kind of assumes one.
3014 struct connection
*d
;
3016 d
= find_host_connection(&md
->iface
->addr
3017 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
3019 for (; d
!= NULL
; d
= d
->hp_next
)
3021 if (d
->kind
== CK_GROUP
)
3027 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
3029 /* must be Road Warrior: we have a winner */
3034 /* Opportunistic or Shunt: pick tightest match */
3035 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
3036 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
3044 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3045 " but no connection has been authorized%s%s"
3046 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
3047 , (policy
!= LEMPTY
) ?
" with policy=" : ""
3048 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
3049 /* XXX notification is in order! */
3052 else if (c
->kind
!= CK_TEMPLATE
)
3054 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3055 " but \"%s\" forbids connection"
3056 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
3057 /* XXX notification is in order! */
3062 /* Create a temporary connection that is a copy of this one.
3063 * His ID isn't declared yet.
3065 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
3068 else if (c
->kind
== CK_TEMPLATE
)
3070 /* Create an instance
3071 * This is a rare case: wildcard peer ID but static peer IP address
3073 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
3077 md
->st
= st
= new_state();
3078 st
->st_connection
= c
;
3079 set_cur_state(st
); /* (caller will reset cur_state) */
3080 st
->st_try
= 0; /* not our job to try again from start */
3081 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
3083 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
3084 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
3086 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3088 st
->st_doi
= ISAKMP_DOI_IPSEC
;
3089 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
3091 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
3093 plog("responding to Main Mode from unknown peer %s:%u"
3094 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
3096 else if (c
->kind
== CK_INSTANCE
)
3098 plog("responding to Main Mode from unknown peer %s"
3099 , ip_str(&c
->spd
.that
.host_addr
));
3103 plog("responding to Main Mode");
3106 /* parse_isakmp_sa also spits out a winning SA into our reply,
3107 * so we have to build our md->reply and emit HDR before calling it.
3110 /* determine how many Vendor ID payloads we will be sending */
3113 if (SEND_CISCO_UNITY_VID
)
3117 /* always send XAUTH Vendor ID */
3119 /* always send DPD Vendor ID */
3121 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3125 * We can't leave this to comm_handle() because we must
3126 * fill in the cookie.
3129 struct isakmp_hdr r_hdr
= md
->hdr
;
3131 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
3132 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
3133 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
3134 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
3135 return STF_INTERNAL_ERROR
;
3138 /* start of SA out */
3140 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
3142 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
3144 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
3145 return STF_INTERNAL_ERROR
;
3148 /* SA body in and out */
3149 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
3150 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
3152 /* if enabled send Pluto Vendor ID */
3155 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3156 , &md
->rbody
, VID_STRONGSWAN
))
3158 return STF_INTERNAL_ERROR
;
3162 /* if enabled send Cisco Unity Vendor ID */
3163 if (SEND_CISCO_UNITY_VID
)
3165 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3166 , &md
->rbody
, VID_CISCO_UNITY
))
3168 return STF_INTERNAL_ERROR
;
3173 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3177 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3178 , &md
->rbody
, VID_OPENPGP
))
3180 return STF_INTERNAL_ERROR
;
3184 /* Announce our ability to do eXtended AUTHentication to the peer */
3185 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3186 , &md
->rbody
, VID_MISC_XAUTH
))
3188 return STF_INTERNAL_ERROR
;
3191 /* Announce our ability to do Dead Peer Detection to the peer */
3192 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3193 , &md
->rbody
, VID_MISC_DPD
))
3195 return STF_INTERNAL_ERROR
;
3198 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3200 /* reply if NAT-Traversal draft is supported */
3201 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3203 if (st
->nat_traversal
3204 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3205 , &md
->rbody
, md
->nat_traversal_vid
))
3207 return STF_INTERNAL_ERROR
;
3211 close_message(&md
->rbody
);
3213 /* save initiator SA for HASH */
3214 clonereplacechunk(st
->st_p1isa
, sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
), "sa in main_inI1_outR1()");
3219 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3220 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3222 * The following are not yet implemented:
3223 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3224 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3225 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3227 * We must verify that the proposal received matches one we sent.
3230 main_inR1_outI2(struct msg_digest
*md
)
3232 struct state
*const st
= md
->st
;
3234 u_int8_t np
= ISAKMP_NEXT_NONE
;
3236 /* verify echoed SA */
3238 u_int32_t ipsecdoisit
;
3239 pb_stream proposal_pbs
;
3240 struct isakmp_proposal proposal
;
3241 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3243 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3244 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3245 if (proposal
.isap_notrans
!= 1)
3247 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3248 , (unsigned)proposal
.isap_notrans
);
3249 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3251 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3252 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3255 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3257 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3258 plog("enabling possible NAT-traversal with method %s"
3259 , bitnamesof(natt_type_bitnames
, st
->nat_traversal
));
3261 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3263 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3264 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3267 /**************** build output packet HDR;KE;Ni ****************/
3270 * We can't leave this to comm_handle() because the isa_np
3271 * depends on the type of Auth (eventually).
3273 echo_hdr(md
, FALSE
, ISAKMP_NEXT_KE
);
3276 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_oakley
.group
3277 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3278 return STF_INTERNAL_ERROR
;
3282 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
3283 , (cur_debugging
& IMPAIR_BUST_MI2
)? ISAKMP_NEXT_VID
: np
, "Ni"))
3284 return STF_INTERNAL_ERROR
;
3286 if (cur_debugging
& IMPAIR_BUST_MI2
)
3288 /* generate a pointless large VID payload to push message over MTU */
3291 if (!out_generic(np
, &isakmp_vendor_id_desc
, &md
->rbody
, &vid_pbs
))
3292 return STF_INTERNAL_ERROR
;
3293 if (!out_zero(1500 /*MTU?*/, &vid_pbs
, "Filler VID"))
3294 return STF_INTERNAL_ERROR
;
3295 close_output_pbs(&vid_pbs
);
3299 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
, np
, "Ni"))
3300 return STF_INTERNAL_ERROR
;
3303 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3305 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE
, &md
->rbody
, md
))
3306 return STF_INTERNAL_ERROR
;
3309 /* finish message */
3310 close_message(&md
->rbody
);
3312 /* Reinsert the state, using the responder cookie we just received */
3314 memcpy(st
->st_rcookie
, md
->hdr
.isa_rcookie
, COOKIE_SIZE
);
3315 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3321 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3323 * The following are not yet implemented:
3324 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3325 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3327 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3328 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3331 main_inI2_outR2(struct msg_digest
*md
)
3333 struct state
*const st
= md
->st
;
3334 pb_stream
*keyex_pbs
= &md
->chain
[ISAKMP_NEXT_KE
]->pbs
;
3336 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3337 bool RSA_auth
= st
->st_oakley
.auth
== OAKLEY_RSA_SIG
3338 || st
->st_oakley
.auth
== XAUTHInitRSA
3339 || st
->st_oakley
.auth
== XAUTHRespRSA
;
3340 bool send_cr
= !no_cr_send
&& RSA_auth
&& !has_preloaded_public_key(st
);
3342 u_int8_t np
= ISAKMP_NEXT_NONE
;
3345 RETURN_STF_FAILURE(accept_KE(&st
->st_gi
, "Gi", st
->st_oakley
.group
, keyex_pbs
));
3348 RETURN_STF_FAILURE(accept_nonce(md
, &st
->st_ni
, "Ni"));
3350 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3352 nat_traversal_natd_lookup(md
);
3354 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3355 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3357 if (st
->nat_traversal
)
3359 nat_traversal_show_result(st
->nat_traversal
, md
->sender_port
);
3361 if (st
->nat_traversal
& NAT_T_WITH_KA
)
3363 nat_traversal_new_ka_event();
3366 /* decode certificate requests */
3367 st
->st_connection
->got_certrequest
= FALSE
;
3368 decode_cr(md
, st
->st_connection
);
3370 /**************** build output packet HDR;KE;Nr ****************/
3375 if (!build_and_ship_KE(st
, &st
->st_gr
, st
->st_oakley
.group
3376 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3377 return STF_INTERNAL_ERROR
;
3381 if (!build_and_ship_nonce(&st
->st_nr
, &md
->rbody
3382 , (cur_debugging
& IMPAIR_BUST_MR2
)? ISAKMP_NEXT_VID
3383 : (send_cr? ISAKMP_NEXT_CR
: np
), "Nr"))
3384 return STF_INTERNAL_ERROR
;
3386 if (cur_debugging
& IMPAIR_BUST_MR2
)
3388 /* generate a pointless large VID payload to push message over MTU */
3391 if (!out_generic((send_cr
)? ISAKMP_NEXT_CR
: np
,
3392 &isakmp_vendor_id_desc
, &md
->rbody
, &vid_pbs
))
3393 return STF_INTERNAL_ERROR
;
3394 if (!out_zero(1500 /*MTU?*/, &vid_pbs
, "Filler VID"))
3395 return STF_INTERNAL_ERROR
;
3396 close_output_pbs(&vid_pbs
);
3400 if (!build_and_ship_nonce(&st
->st_nr
, &md
->rbody
,
3401 (send_cr
)? ISAKMP_NEXT_CR
: np
, "Nr"))
3402 return STF_INTERNAL_ERROR
;
3408 if (st
->st_connection
->kind
== CK_PERMANENT
)
3410 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3411 , st
->st_connection
->spd
.that
.ca
3413 return STF_INTERNAL_ERROR
;
3417 generalName_t
*ca
= NULL
;
3419 if (collect_rw_ca_candidates(md
, &ca
))
3423 for (gn
= ca
; gn
!= NULL
; gn
= gn
->next
)
3425 if (!build_and_ship_CR(CERT_X509_SIGNATURE
, gn
->name
3427 , gn
->next
== NULL ? np
: ISAKMP_NEXT_CR
))
3428 return STF_INTERNAL_ERROR
;
3430 free_generalNames(ca
, FALSE
);
3434 if (!build_and_ship_CR(CERT_X509_SIGNATURE
, empty_chunk
3436 return STF_INTERNAL_ERROR
;
3441 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3443 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE
, &md
->rbody
, md
))
3444 return STF_INTERNAL_ERROR
;
3447 /* finish message */
3448 close_message(&md
->rbody
);
3450 /* next message will be encrypted, but not this one.
3451 * We could defer this calculation.
3453 compute_dh_shared(st
, st
->st_gi
, st
->st_oakley
.group
);
3454 if (!generate_skeyids_iv(st
))
3455 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3462 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3463 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3465 * The following are not yet implemented.
3466 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3468 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3472 main_inR2_outI3(struct msg_digest
*md
)
3474 struct state
*const st
= md
->st
;
3475 pb_stream
*const keyex_pbs
= &md
->chain
[ISAKMP_NEXT_KE
]->pbs
;
3476 pb_stream id_pbs
; /* ID Payload; also used for hash calculation */
3478 certpolicy_t cert_policy
= st
->st_connection
->spd
.this.sendcert
;
3479 cert_t mycert
= st
->st_connection
->spd
.this.cert
;
3480 bool requested
, send_cert
, send_cr
;
3482 bool RSA_auth
= st
->st_oakley
.auth
== OAKLEY_RSA_SIG
3483 || st
->st_oakley
.auth
== XAUTHInitRSA
3484 || st
->st_oakley
.auth
== XAUTHRespRSA
;
3486 int auth_payload
= RSA_auth ? ISAKMP_NEXT_SIG
: ISAKMP_NEXT_HASH
;
3489 RETURN_STF_FAILURE(accept_KE(&st
->st_gr
, "Gr", st
->st_oakley
.group
, keyex_pbs
));
3492 RETURN_STF_FAILURE(accept_nonce(md
, &st
->st_nr
, "Nr"));
3494 /* decode certificate requests */
3495 st
->st_connection
->got_certrequest
= FALSE
;
3496 decode_cr(md
, st
->st_connection
);
3498 /* free collected certificate requests since as initiator
3499 * we don't heed them anyway
3501 free_generalNames(st
->st_connection
->requested_ca
, TRUE
);
3502 st
->st_connection
->requested_ca
= NULL
;
3504 /* send certificate if auth is RSA, we have one and we want
3505 * or are requested to send it
3507 requested
= cert_policy
== CERT_SEND_IF_ASKED
3508 && st
->st_connection
->got_certrequest
;
3509 send_cert
= RSA_auth
&& mycert
.type
!= CERT_NONE
3510 && (cert_policy
== CERT_ALWAYS_SEND
|| requested
);
3512 /* send certificate request if we don't have a preloaded RSA public key */
3513 send_cr
= !no_cr_send
&& send_cert
&& !has_preloaded_public_key(st
);
3515 /* done parsing; initialize crypto */
3516 compute_dh_shared(st
, st
->st_gr
, st
->st_oakley
.group
);
3517 if (!generate_skeyids_iv(st
))
3518 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3520 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3522 nat_traversal_natd_lookup(md
);
3524 if (st
->nat_traversal
)
3526 nat_traversal_show_result(st
->nat_traversal
, md
->sender_port
);
3528 if (st
->nat_traversal
& NAT_T_WITH_KA
)
3530 nat_traversal_new_ka_event();
3533 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3534 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3540 struct isakmp_ipsec_id id_hd
;
3543 build_id_payload(&id_hd
, &id_b
, &st
->st_connection
->spd
.this);
3544 id_hd
.isaiid_np
= (send_cert
)? ISAKMP_NEXT_CERT
: auth_payload
;
3545 if (!out_struct(&id_hd
, &isakmp_ipsec_identification_desc
, &md
->rbody
, &id_pbs
)
3546 || !out_chunk(id_b
, &id_pbs
, "my identity"))
3547 return STF_INTERNAL_ERROR
;
3548 close_output_pbs(&id_pbs
);
3555 DBG_log("our certificate policy is %s"
3556 , enum_name(&cert_policy_names
, cert_policy
))
3558 if (mycert
.type
!= CERT_NONE
)
3560 const char *request_text
= "";
3562 if (cert_policy
== CERT_SEND_IF_ASKED
)
3563 request_text
= (send_cert
)?
"upon request":"without request";
3564 plog("we have a cert %s sending it %s"
3565 , send_cert?
"and are":"but are not", request_text
);
3569 plog("we don't have a cert");
3576 struct isakmp_cert cert_hd
;
3577 cert_hd
.isacert_np
= (send_cr
)? ISAKMP_NEXT_CR
: ISAKMP_NEXT_SIG
;
3578 cert_hd
.isacert_type
= mycert
.type
;
3580 if (!out_struct(&cert_hd
, &isakmp_ipsec_certificate_desc
, &md
->rbody
, &cert_pbs
))
3581 return STF_INTERNAL_ERROR
;
3582 if (!out_chunk(get_mycert(mycert
), &cert_pbs
, "CERT"))
3583 return STF_INTERNAL_ERROR
;
3584 close_output_pbs(&cert_pbs
);
3590 if (!build_and_ship_CR(mycert
.type
, st
->st_connection
->spd
.that
.ca
3591 , &md
->rbody
, ISAKMP_NEXT_SIG
))
3592 return STF_INTERNAL_ERROR
;
3595 /* HASH_I or SIG_I out */
3597 u_char hash_val
[MAX_DIGEST_LEN
];
3598 size_t hash_len
= main_mode_hash(st
, hash_val
, TRUE
, &id_pbs
);
3600 if (auth_payload
== ISAKMP_NEXT_HASH
)
3603 if (!out_generic_raw(ISAKMP_NEXT_NONE
, &isakmp_hash_desc
, &md
->rbody
3604 , hash_val
, hash_len
, "HASH_I"))
3605 return STF_INTERNAL_ERROR
;
3610 u_char sig_val
[RSA_MAX_OCTETS
];
3611 size_t sig_len
= RSA_sign_hash(st
->st_connection
3612 , sig_val
, hash_val
, hash_len
);
3616 loglog(RC_LOG_SERIOUS
, "unable to locate my private key for RSA Signature");
3617 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3620 if (!out_generic_raw(ISAKMP_NEXT_NONE
, &isakmp_signature_desc
3621 , &md
->rbody
, sig_val
, sig_len
, "SIG_I"))
3622 return STF_INTERNAL_ERROR
;
3626 /* encrypt message, except for fixed part of header */
3628 /* st_new_iv was computed by generate_skeyids_iv */
3629 if (!encrypt_message(&md
->rbody
, st
))
3630 return STF_INTERNAL_ERROR
; /* ??? we may be partly committed */
3635 /* Shared logic for asynchronous lookup of DNS KEY records.
3636 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3639 enum key_oppo_step
{
3647 struct key_continuation
{
3648 struct adns_continuation ac
; /* common prefix */
3649 struct msg_digest
*md
;
3650 enum key_oppo_step step
;
3655 typedef stf_status (key_tail_fn
)(struct msg_digest
*md
3656 , struct key_continuation
*kc
);
3658 report_key_dns_failure(struct id
*id
, err_t ugh
)
3660 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
3662 (void) idtoa(id
, id_buf
, sizeof(id_buf
));
3663 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
3664 "; DNS search for KEY failed (%s)", id_buf
, ugh
);
3668 /* Processs the Main Mode ID Payload and the Authenticator
3669 * (Hash or Signature Payload).
3670 * If a DNS query is still needed to get the other host's public key,
3671 * the query is initiated and STF_SUSPEND is returned.
3672 * Note: parameter kc is a continuation containing the results from
3673 * the previous DNS query, or NULL indicating no query has been issued.
3676 main_id_and_auth(struct msg_digest
*md
3677 , bool initiator
/* are we the Initiator? */
3678 , cont_fn_t cont_fn
/* continuation function */
3679 , const struct key_continuation
*kc
/* current state, can be NULL */
3682 struct state
*st
= md
->st
;
3683 u_char hash_val
[MAX_DIGEST_LEN
];
3686 stf_status r
= STF_OK
;
3689 if (!decode_peer_id(md
, &peer
))
3690 return STF_FAIL
+ INVALID_ID_INFORMATION
;
3692 /* Hash the ID Payload.
3693 * main_mode_hash requires idpl->cur to be at end of payload
3694 * so we temporarily set if so.
3697 pb_stream
*idpl
= &md
->chain
[ISAKMP_NEXT_ID
]->pbs
;
3698 u_int8_t
*old_cur
= idpl
->cur
;
3700 idpl
->cur
= idpl
->roof
;
3701 hash_len
= main_mode_hash(st
, hash_val
, !initiator
, idpl
);
3702 idpl
->cur
= old_cur
;
3705 switch (st
->st_oakley
.auth
)
3707 case OAKLEY_PRESHARED_KEY
:
3708 case XAUTHInitPreShared
:
3709 case XAUTHRespPreShared
:
3711 pb_stream
*const hash_pbs
= &md
->chain
[ISAKMP_NEXT_HASH
]->pbs
;
3713 if (pbs_left(hash_pbs
) != hash_len
3714 || memcmp(hash_pbs
->cur
, hash_val
, hash_len
) != 0)
3716 DBG_cond_dump(DBG_CRYPT
, "received HASH:"
3717 , hash_pbs
->cur
, pbs_left(hash_pbs
));
3718 loglog(RC_LOG_SERIOUS
, "received Hash Payload does not match computed value");
3719 /* XXX Could send notification back */
3720 r
= STF_FAIL
+ INVALID_HASH_INFORMATION
;
3725 case OAKLEY_RSA_SIG
:
3728 r
= RSA_check_signature(&peer
, st
, hash_val
, hash_len
3729 , &md
->chain
[ISAKMP_NEXT_SIG
]->pbs
3731 , kc
== NULL? NULL
: kc
->ac
.keys_from_dns
3732 #endif /* USE_KEYRR */
3733 , kc
== NULL? NULL
: kc
->ac
.gateways_from_dns
3736 if (r
== STF_SUSPEND
)
3738 /* initiate/resume asynchronous DNS lookup for key */
3739 struct key_continuation
*nkc
3740 = alloc_thing(struct key_continuation
, "key continuation");
3741 enum key_oppo_step step_done
= kc
== NULL? kos_null
: kc
->step
;
3744 /* Record that state is used by a suspended md */
3745 passert(st
->st_suspended_md
== NULL
);
3746 st
->st_suspended_md
= md
;
3748 nkc
->failure_ok
= FALSE
;
3754 /* first try: look for the TXT records */
3755 nkc
->step
= kos_his_txt
;
3757 nkc
->failure_ok
= TRUE
;
3759 ugh
= start_adns_query(&peer
3760 , &peer
/* SG itself */
3768 /* second try: look for the KEY records */
3769 nkc
->step
= kos_his_key
;
3770 ugh
= start_adns_query(&peer
3771 , NULL
/* no sgw for KEY */
3776 #endif /* USE_KEYRR */
3779 bad_case(step_done
);
3784 report_key_dns_failure(&peer
, ugh
);
3785 st
->st_suspended_md
= NULL
;
3786 r
= STF_FAIL
+ INVALID_KEY_INFORMATION
;
3792 bad_case(st
->st_oakley
.auth
);
3797 DBG(DBG_CRYPT
, DBG_log("authentication succeeded"));
3800 * With the peer ID known, let's see if we need to switch connections.
3802 if (!switch_connection(md
, &peer
, initiator
))
3803 return STF_FAIL
+ INVALID_ID_INFORMATION
;
3808 /* This continuation is called as part of either
3809 * the main_inI3_outR3 state or main_inR3 state.
3811 * The "tail" function is the corresponding tail
3812 * function main_inI3_outR3_tail | main_inR3_tail,
3813 * either directly when the state is started, or via
3814 * adns continuation.