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 an XAUTH VID?
86 #define SEND_XAUTH_VID 1
87 #else /* !XAUTH_VID */
88 #define SEND_XAUTH_VID 0
89 #endif /* !XAUTH_VID */
92 * are we sending a Cisco Unity VID?
95 #define SEND_CISCO_UNITY_VID 1
96 #else /* !CISCO_QUIRKS */
97 #define SEND_CISCO_UNITY_VID 0
98 #endif /* !CISCO_QUIRKS */
100 /* MAGIC: perform f, a function that returns notification_t
101 * and return from the ENCLOSING stf_status returning function if it fails.
103 #define RETURN_STF_FAILURE(f) \
104 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
106 /* create output HDR as replica of input HDR */
108 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
110 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
112 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
114 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
115 /* some day, we may have to set r_hdr.isa_version */
117 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
118 impossible(); /* surely must have room and be well-formed */
121 /* Compute DH shared secret from our local secret and the peer's public value.
122 * We make the leap that the length should be that of the group
123 * (see quoted passage at start of ACCEPT_KE).
126 compute_dh_shared(struct state
*st
, const chunk_t g
127 , const struct oakley_group_desc
*group
)
129 MP_INT mp_g
, mp_shared
;
130 struct timeval tv0
, tv1
;
131 unsigned long tv_diff
;
133 gettimeofday(&tv0
, NULL
);
134 passert(st
->st_sec_in_use
);
135 n_to_mpz(&mp_g
, g
.ptr
, g
.len
);
136 mpz_init(&mp_shared
);
137 mpz_powm(&mp_shared
, &mp_g
, &st
->st_sec
, group
->modulus
);
139 freeanychunk(st
->st_shared
); /* happens in odd error cases */
140 st
->st_shared
= mpz_to_n(&mp_shared
, group
->bytes
);
141 mpz_clear(&mp_shared
);
142 gettimeofday(&tv1
, NULL
);
143 tv_diff
=(tv1
.tv_sec
- tv0
.tv_sec
) * 1000000 + (tv1
.tv_usec
- tv0
.tv_usec
);
145 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
146 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
149 /* if took more than 200 msec ... */
150 if (tv_diff
> 200000) {
151 loglog(RC_LOG_SERIOUS
, "WARNING: compute_dh_shared(): for %s took "
153 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
157 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
160 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
161 * the corresponding public value (g). This is emitted as a KE payload.
164 build_and_ship_KE(struct state
*st
, chunk_t
*g
165 , const struct oakley_group_desc
*group
, pb_stream
*outs
, u_int8_t np
)
167 if (!st
->st_sec_in_use
)
169 u_char tmp
[LOCALSECRETSIZE
];
172 get_rnd_bytes(tmp
, LOCALSECRETSIZE
);
173 st
->st_sec_in_use
= TRUE
;
174 n_to_mpz(&st
->st_sec
, tmp
, LOCALSECRETSIZE
);
177 mpz_powm(&mp_g
, &groupgenerator
, &st
->st_sec
, group
->modulus
);
178 freeanychunk(*g
); /* happens in odd error cases */
179 *g
= mpz_to_n(&mp_g
, group
->bytes
);
182 DBG_dump("Local DH secret:\n", tmp
, LOCALSECRETSIZE
);
183 DBG_dump_chunk("Public DH value sent:\n", *g
));
185 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
190 * Check and accept DH public value (Gi or Gr) from peer's message.
191 * According to RFC2409 "The Internet key exchange (IKE)" 5:
192 * The Diffie-Hellman public value passed in a KE payload, in either
193 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
194 * Diffie-Hellman group enforced, if necessary, by pre-pending the
197 static notification_t
198 accept_KE(chunk_t
*dest
, const char *val_name
199 , const struct oakley_group_desc
*gr
202 if (pbs_left(pbs
) != gr
->bytes
)
204 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
205 , (unsigned) pbs_left(pbs
), (unsigned) gr
->bytes
);
206 /* XXX Could send notification back */
207 return INVALID_KEY_INFORMATION
;
209 clonereplacechunk(*dest
, pbs
->cur
, pbs_left(pbs
), val_name
);
210 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
211 return NOTHING_WRONG
;
216 * Check and accept optional Quick Mode KE payload for PFS.
217 * Extends ACCEPT_PFS to check whether KE is allowed or required.
219 static notification_t
220 accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
221 , const char *val_name
, const char *msg_name
)
223 struct state
*st
= md
->st
;
224 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
228 if (st
->st_pfs_group
!= NULL
)
230 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
231 return INVALID_KEY_INFORMATION
;
236 if (st
->st_pfs_group
== NULL
)
238 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
240 return INVALID_KEY_INFORMATION
;
242 if (ke_pd
->next
!= NULL
)
244 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
245 return INVALID_KEY_INFORMATION
; /* ??? */
247 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
249 return NOTHING_WRONG
;
253 build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
257 setchunk(*n
, alloc_bytes(DEFAULT_NONCE_SIZE
, name
), DEFAULT_NONCE_SIZE
);
258 get_rnd_bytes(n
->ptr
, DEFAULT_NONCE_SIZE
);
259 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
263 collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
265 struct connection
*d
= find_host_connection(&md
->iface
->addr
266 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
268 for (; d
!= NULL
; d
= d
->hp_next
)
270 /* must be a road warrior connection */
271 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
272 && d
->spd
.that
.ca
.ptr
!= NULL
)
275 bool new_entry
= TRUE
;
277 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
279 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
287 gn
= alloc_thing(generalName_t
, "generalName");
288 gn
->kind
= GN_DIRECTORY_NAME
;
289 gn
->name
= d
->spd
.that
.ca
;
299 build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
, u_int8_t np
)
302 struct isakmp_cr cr_hd
;
304 cr_hd
.isacr_type
= type
;
306 /* build CR header */
307 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
312 /* build CR body containing the distinguished name of the CA */
313 if (!out_chunk(ca
, &cr_pbs
, "CA"))
316 close_output_pbs(&cr_pbs
);
320 /* Send a notification to the peer. We could decide
321 * whether to send the notification, based on the type and the
322 * destination, if we care to.
325 send_notification(struct state
*sndst
, u_int16_t type
, struct state
*encst
,
326 msgid_t msgid
, u_char
*icookie
, u_char
*rcookie
,
327 u_char
*spi
, size_t spisize
, u_char protoid
)
330 pb_stream pbs
, r_hdr_pbs
;
331 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
332 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
334 passert((sndst
) && (sndst
->st_connection
));
336 plog("sending %snotification %s to %s:%u"
337 , encst ?
"encrypted " : ""
338 , enum_name(¬ification_names
, type
)
339 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
340 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
342 memset(buffer
, 0, sizeof(buffer
));
343 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
347 struct isakmp_hdr hdr
;
349 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
350 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
351 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
352 hdr
.isa_msgid
= msgid
;
353 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
355 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
357 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
358 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
362 /* HASH -- value to be filled later */
366 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
369 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
371 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
373 close_output_pbs(&hash_pbs
);
374 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
377 /* Notification Payload */
380 struct isakmp_notification isan
;
382 isan
.isan_doi
= ISAKMP_DOI_IPSEC
;
383 isan
.isan_np
= ISAKMP_NEXT_NONE
;
384 isan
.isan_type
= type
;
385 isan
.isan_spisize
= spisize
;
386 isan
.isan_protoid
= protoid
;
388 if (!out_struct(&isan
, &isakmp_notification_desc
, &r_hdr_pbs
, ¬_pbs
)
389 || !out_raw(spi
, spisize
, ¬_pbs
, "spi"))
391 close_output_pbs(¬_pbs
);
394 /* calculate hash value and patch into Hash Payload */
398 hmac_init_chunk(&ctx
, encst
->st_oakley
.hasher
, encst
->st_skeyid_a
);
399 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
400 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
401 hmac_final(r_hashval
, &ctx
);
404 DBG_log("HASH computed:");
405 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
409 /* Encrypt message (preserve st_iv and st_new_iv) */
412 u_char old_iv
[MAX_DIGEST_LEN
];
413 u_char new_iv
[MAX_DIGEST_LEN
];
415 u_int old_iv_len
= encst
->st_iv_len
;
416 u_int new_iv_len
= encst
->st_new_iv_len
;
418 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
421 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
422 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
424 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
426 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
427 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
429 init_phase2_iv(encst
, &msgid
);
430 if (!encrypt_message(&r_hdr_pbs
, encst
))
433 /* restore preserved st_iv and st_new_iv */
434 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
435 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
436 encst
->st_iv_len
= old_iv_len
;
437 encst
->st_new_iv_len
= new_iv_len
;
441 close_output_pbs(&r_hdr_pbs
);
444 /* Send packet (preserve st_tpacket) */
446 chunk_t saved_tpacket
= sndst
->st_tpacket
;
448 setchunk(sndst
->st_tpacket
, pbs
.start
, pbs_offset(&pbs
));
449 send_packet(sndst
, "ISAKMP notify");
450 sndst
->st_tpacket
= saved_tpacket
;
455 send_notification_from_state(struct state
*st
, enum state_kind state
,
462 if (state
== STATE_UNDEFINED
)
463 state
= st
->st_state
;
467 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
468 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
)))
470 loglog(RC_LOG_SERIOUS
,
471 "no Phase1 state for Quick mode notification");
474 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
475 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
477 else if (IS_ISAKMP_ENCRYPTED(state
) && st
->st_enc_key
.ptr
!= NULL
)
479 send_notification(st
, type
, st
, generate_msgid(st
),
480 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
484 /* no ISAKMP SA established - don't encrypt notification */
485 send_notification(st
, type
, NULL
, 0,
486 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
491 send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
494 * Create a dummy state to be able to use send_packet in
498 * st_connection->that.host_addr
499 * st_connection->that.host_port
500 * st_connection->interface
503 struct connection cnx
;
507 memset(&st
, 0, sizeof(st
));
508 memset(&cnx
, 0, sizeof(cnx
));
509 st
.st_connection
= &cnx
;
510 cnx
.spd
.that
.host_addr
= md
->sender
;
511 cnx
.spd
.that
.host_port
= md
->sender_port
;
512 cnx
.interface
= md
->iface
;
514 send_notification(&st
, type
, NULL
, 0,
515 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
518 /* Send a Delete Notification to announce deletion of ISAKMP SA or
519 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
520 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
523 send_delete(struct state
*st
)
530 ip_said said
[EM_MAXRELSPIS
];
533 *r_hashval
, /* where in reply to jam hash value */
534 *r_hash_start
; /* start of what is to be hashed */
535 bool isakmp_sa
= FALSE
;
537 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
539 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
542 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
546 if (st
->st_ah
.present
)
548 ns
->spi
= st
->st_ah
.our_spi
;
549 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
550 ns
->proto
= PROTO_IPSEC_AH
;
553 if (st
->st_esp
.present
)
555 ns
->spi
= st
->st_esp
.our_spi
;
556 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
557 ns
->proto
= PROTO_IPSEC_ESP
;
561 passert(ns
!= said
); /* there must be some SAs to delete */
563 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
570 return; /* nothing to do */
573 msgid
= generate_msgid(p1st
);
576 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
580 struct isakmp_hdr hdr
;
582 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
583 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
584 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
585 hdr
.isa_msgid
= msgid
;
586 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
587 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
588 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
589 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
593 /* HASH -- value to be filled later */
597 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
599 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
600 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
602 close_output_pbs(&hash_pbs
);
603 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
606 /* Delete Payloads */
610 struct isakmp_delete isad
;
611 u_char isakmp_spi
[2*COOKIE_SIZE
];
613 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
614 isad
.isad_np
= ISAKMP_NEXT_NONE
;
615 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
616 isad
.isad_protoid
= PROTO_ISAKMP
;
619 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
620 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
622 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
623 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
625 close_output_pbs(&del_pbs
);
633 struct isakmp_delete isad
;
636 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
637 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
638 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
639 isad
.isad_protoid
= ns
->proto
;
642 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
643 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
645 close_output_pbs(&del_pbs
);
649 /* calculate hash value and patch into Hash Payload */
652 hmac_init_chunk(&ctx
, p1st
->st_oakley
.hasher
, p1st
->st_skeyid_a
);
653 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
654 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
655 hmac_final(r_hashval
, &ctx
);
658 DBG_log("HASH(1) computed:");
659 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
663 /* Do a dance to avoid needing a new state object.
664 * We use the Phase 1 State. This is the one with right
666 * The tricky bits are:
667 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
668 * - we need to preserve (save/restore) st_tpacket.
671 u_char old_iv
[MAX_DIGEST_LEN
];
672 chunk_t saved_tpacket
= p1st
->st_tpacket
;
674 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
675 init_phase2_iv(p1st
, &msgid
);
677 if (!encrypt_message(&r_hdr_pbs
, p1st
))
680 setchunk(p1st
->st_tpacket
, reply_pbs
.start
, pbs_offset(&reply_pbs
));
681 send_packet(p1st
, "delete notify");
682 p1st
->st_tpacket
= saved_tpacket
;
684 /* get back old IV for this state */
685 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
690 accept_delete(struct state
*st
, struct msg_digest
*md
, struct payload_digest
*p
)
692 struct isakmp_delete
*d
= &(p
->payload
.delete);
698 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
702 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
704 /* can't happen (if msg is encrypt), but just to be sure */
705 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
706 "ISAKMP SA not established");
710 if (d
->isad_nospi
== 0)
712 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
716 switch (d
->isad_protoid
)
719 sizespi
= 2 * COOKIE_SIZE
;
722 case PROTO_IPSEC_ESP
:
723 sizespi
= sizeof(ipsec_spi_t
);
726 /* nothing interesting to delete */
729 loglog(RC_LOG_SERIOUS
730 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
731 , enum_show(&protocol_names
, d
->isad_protoid
));
735 if (d
->isad_spisize
!= sizespi
)
737 loglog(RC_LOG_SERIOUS
738 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
739 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
743 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
745 loglog(RC_LOG_SERIOUS
746 , "ignoring Delete SA payload: invalid payload size");
750 for (i
= 0; i
< d
->isad_nospi
; i
++)
752 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
754 if (d
->isad_protoid
== PROTO_ISAKMP
)
759 struct state
*dst
= find_state(spi
/*iCookie*/
760 , spi
+COOKIE_SIZE
/*rCookie*/
761 , &st
->st_connection
->spd
.that
.host_addr
766 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
767 "ISAKMP SA not found (maybe expired)");
769 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
771 /* we've not authenticated the relevant identities */
772 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
773 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
777 struct connection
*oldc
;
779 oldc
= cur_connection
;
780 set_cur_connection(dst
->st_connection
);
782 if (nat_traversal_enabled
)
783 nat_traversal_change_port_lookup(md
, dst
);
785 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
786 "deleting ISAKMP State #%lu", dst
->st_serialno
);
788 set_cur_connection(oldc
);
797 struct state
*dst
= find_phase2_state_to_delete(st
799 , *(ipsec_spi_t
*)spi
/* network order */
804 loglog(RC_LOG_SERIOUS
805 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
806 , enum_show(&protocol_names
, d
->isad_protoid
)
807 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
808 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
812 struct connection
*rc
= dst
->st_connection
;
813 struct connection
*oldc
;
815 oldc
= cur_connection
;
816 set_cur_connection(rc
);
818 if (nat_traversal_enabled
)
819 nat_traversal_change_port_lookup(md
, dst
);
821 if (rc
->newest_ipsec_sa
== dst
->st_serialno
822 && (rc
->policy
& POLICY_UP
))
824 /* Last IPSec SA for a permanent connection that we
825 * have initiated. Replace it in a few seconds.
827 * Useful if the other peer is rebooting.
829 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
830 if (dst
->st_event
!= NULL
831 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
832 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
834 /* Patch from Angus Lees to ignore retransmited
837 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
838 "already replacing IPSEC State #%lu in %d seconds"
839 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
843 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
844 "replace IPSEC State #%lu in %d seconds"
845 , dst
->st_serialno
, DELETE_SA_DELAY
);
846 dst
->st_margin
= DELETE_SA_DELAY
;
848 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
853 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
854 "deleting IPSEC State #%lu"
855 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
860 /* reset connection */
861 set_cur_connection(oldc
);
867 /* The whole message must be a multiple of 4 octets.
868 * I'm not sure where this is spelled out, but look at
869 * rfc2408 3.6 Transform Payload.
870 * Note: it talks about 4 BYTE boundaries!
873 close_message(pb_stream
*pbs
)
875 size_t padding
= pad_up(pbs_offset(pbs
), 4);
878 (void) out_zero(padding
, pbs
, "message padding");
879 close_output_pbs(pbs
);
882 /* Initiate an Oakley Main Mode exchange.
884 * Note: this is not called from demux.c
887 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
888 , lset_t policy
, unsigned long try)
890 struct state
*st
= new_state();
891 pb_stream reply
; /* not actually a reply, but you know what I mean */
894 int vids_to_send
= 0;
896 /* set up new state */
897 st
->st_connection
= c
;
898 set_cur_state(st
); /* we must reset before exit */
899 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
900 st
->st_whack_sock
= whack_sock
;
902 st
->st_state
= STATE_MAIN_I1
;
904 /* determine how many Vendor ID payloads we will be sending */
907 if (SEND_CISCO_UNITY_VID
)
909 if (c
->spd
.this.cert
.type
== CERT_PGP
)
913 /* always send DPD Vendor ID */
915 if (nat_traversal_enabled
)
918 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
920 insert_state(st
); /* needs cookies, connection, and msgid (0) */
922 if (HAS_IPSEC_POLICY(policy
))
923 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
924 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
926 if (predecessor
== NULL
)
927 plog("initiating Main Mode");
929 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
932 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
936 struct isakmp_hdr hdr
;
938 zero(&hdr
); /* default to 0 */
939 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
940 hdr
.isa_np
= ISAKMP_NEXT_SA
;
941 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
942 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
943 /* R-cookie, flags and MessageID are left zero */
945 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
948 return STF_INTERNAL_ERROR
;
954 u_char
*sa_start
= rbody
.cur
;
955 lset_t auth_policy
= policy
& POLICY_ID_AUTH_MASK
;
957 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
958 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
961 return STF_INTERNAL_ERROR
;
964 /* save initiator SA for later HASH */
965 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
966 clonetochunk(st
->st_p1isa
, sa_start
, rbody
.cur
- sa_start
967 , "sa in main_outI1");
970 /* if enabled send Pluto Vendor ID */
973 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
974 , &rbody
, VID_STRONGSWAN
))
977 return STF_INTERNAL_ERROR
;
981 /* if enabled send Cisco Unity Vendor ID */
982 if (SEND_CISCO_UNITY_VID
)
984 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
985 , &rbody
, VID_CISCO_UNITY
))
988 return STF_INTERNAL_ERROR
;
991 /* if we have an OpenPGP certificate we assume an
992 * OpenPGP peer and have to send the Vendor ID
994 if (c
->spd
.this.cert
.type
== CERT_PGP
)
996 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
997 , &rbody
, VID_OPENPGP
))
1000 return STF_INTERNAL_ERROR
;
1004 /* Announce our ability to do eXtended AUTHentication to the peer */
1007 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1008 , &rbody
, VID_MISC_XAUTH
))
1011 return STF_INTERNAL_ERROR
;
1015 /* Announce our ability to do Dead Peer Detection to the peer */
1017 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1018 , &rbody
, VID_MISC_DPD
))
1021 return STF_INTERNAL_ERROR
;
1025 if (nat_traversal_enabled
)
1027 /* Add supported NAT-Traversal VID */
1028 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1032 return STF_INTERNAL_ERROR
;
1036 close_message(&rbody
);
1037 close_output_pbs(&reply
);
1039 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
1040 , "reply packet for main_outI1");
1044 send_packet(st
, "main_outI1");
1046 /* Set up a retransmission event, half a minute henceforth */
1048 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1050 if (predecessor
!= NULL
)
1052 update_pending(predecessor
, st
);
1053 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1054 , "%s: initiate, replacing #%lu"
1055 , enum_name(&state_names
, st
->st_state
)
1056 , predecessor
->st_serialno
);
1060 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1061 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1068 ipsecdoi_initiate(int whack_sock
1069 , struct connection
*c
1072 , so_serial_t replacing
)
1074 /* If there's already an ISAKMP SA established, use that and
1075 * go directly to Quick Mode. We are even willing to use one
1076 * that is still being negotiated, but only if we are the Initiator
1077 * (thus we can be sure that the IDs are not going to change;
1078 * other issues around intent might matter).
1079 * Note: there is no way to initiate with a Road Warrior.
1081 struct state
*st
= find_phase1_state(c
1082 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1086 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1088 else if (HAS_IPSEC_POLICY(policy
))
1090 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1092 /* leave our Phase 2 negotiation pending */
1093 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1097 /* ??? we assume that peer_nexthop_sin isn't important:
1098 * we already have it from when we negotiated the ISAKMP SA!
1099 * It isn't clear what to do with the error return.
1101 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1106 close_any(whack_sock
);
1110 /* Replace SA with a fresh one that is similar
1112 * Shares some logic with ipsecdoi_initiate, but not the same!
1113 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1114 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1115 * ISAKMP SA if needed.
1116 * - duplicate whack fd, if live.
1117 * Does not delete the old state -- someone else will do that.
1120 ipsecdoi_replace(struct state
*st
, unsigned long try)
1122 int whack_sock
= dup_any(st
->st_whack_sock
);
1123 lset_t policy
= st
->st_policy
;
1125 if (IS_PHASE1(st
->st_state
))
1127 passert(!HAS_IPSEC_POLICY(policy
));
1128 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1132 /* Add features of actual old state to policy. This ensures
1133 * that rekeying doesn't downgrade security. I admit that
1134 * this doesn't capture everything.
1136 if (st
->st_pfs_group
!= NULL
)
1137 policy
|= POLICY_PFS
;
1138 if (st
->st_ah
.present
)
1140 policy
|= POLICY_AUTHENTICATE
;
1141 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1142 policy
|= POLICY_TUNNEL
;
1144 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1146 policy
|= POLICY_ENCRYPT
;
1147 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1148 policy
|= POLICY_TUNNEL
;
1150 if (st
->st_ipcomp
.present
)
1152 policy
|= POLICY_COMPRESS
;
1153 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1154 policy
|= POLICY_TUNNEL
;
1156 passert(HAS_IPSEC_POLICY(policy
));
1157 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1162 /* SKEYID for preshared keys.
1163 * See draft-ietf-ipsec-ike-01.txt 4.1
1166 skeyid_preshared(struct state
*st
)
1168 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1172 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1177 struct hmac_ctx ctx
;
1179 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, *pss
);
1180 hmac_update_chunk(&ctx
, st
->st_ni
);
1181 hmac_update_chunk(&ctx
, st
->st_nr
);
1182 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_preshared()", &ctx
);
1188 skeyid_digisig(struct state
*st
)
1190 struct hmac_ctx ctx
;
1193 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1194 * so we have to build a temporary concatentation.
1196 nir
.len
= st
->st_ni
.len
+ st
->st_nr
.len
;
1197 nir
.ptr
= alloc_bytes(nir
.len
, "Ni + Nr in skeyid_digisig");
1198 memcpy(nir
.ptr
, st
->st_ni
.ptr
, st
->st_ni
.len
);
1199 memcpy(nir
.ptr
+st
->st_ni
.len
, st
->st_nr
.ptr
, st
->st_nr
.len
);
1200 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, nir
);
1203 hmac_update_chunk(&ctx
, st
->st_shared
);
1204 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_digisig()", &ctx
);
1208 /* Generate the SKEYID_* and new IV
1209 * See draft-ietf-ipsec-ike-01.txt 4.1
1212 generate_skeyids_iv(struct state
*st
)
1214 /* Generate the SKEYID */
1215 switch (st
->st_oakley
.auth
)
1217 case OAKLEY_PRESHARED_KEY
:
1218 case XAUTHInitPreShared
:
1219 case XAUTHRespPreShared
:
1220 if (!skeyid_preshared(st
))
1224 case OAKLEY_RSA_SIG
:
1227 if (!skeyid_digisig(st
))
1231 case OAKLEY_DSS_SIG
:
1234 case OAKLEY_RSA_ENC
:
1235 case OAKLEY_RSA_ENC_REV
:
1236 case OAKLEY_ELGAMAL_ENC
:
1237 case OAKLEY_ELGAMAL_ENC_REV
:
1241 bad_case(st
->st_oakley
.auth
);
1244 /* generate SKEYID_* from SKEYID */
1246 struct hmac_ctx ctx
;
1248 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1251 hmac_update_chunk(&ctx
, st
->st_shared
);
1252 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1253 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1254 hmac_update(&ctx
, "\0", 1);
1255 hmac_final_chunk(st
->st_skeyid_d
, "st_skeyid_d in generate_skeyids_iv()", &ctx
);
1259 hmac_update_chunk(&ctx
, st
->st_skeyid_d
);
1260 hmac_update_chunk(&ctx
, st
->st_shared
);
1261 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1262 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1263 hmac_update(&ctx
, "\1", 1);
1264 hmac_final_chunk(st
->st_skeyid_a
, "st_skeyid_a in generate_skeyids_iv()", &ctx
);
1268 hmac_update_chunk(&ctx
, st
->st_skeyid_a
);
1269 hmac_update_chunk(&ctx
, st
->st_shared
);
1270 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1271 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1272 hmac_update(&ctx
, "\2", 1);
1273 hmac_final_chunk(st
->st_skeyid_e
, "st_skeyid_e in generate_skeyids_iv()", &ctx
);
1278 union hash_ctx hash_ctx
;
1279 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1281 st
->st_new_iv_len
= h
->hash_digest_size
;
1282 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1285 DBG_dump_chunk("DH_i:", st
->st_gi
);
1286 DBG_dump_chunk("DH_r:", st
->st_gr
);
1288 h
->hash_init(&hash_ctx
);
1289 h
->hash_update(&hash_ctx
, st
->st_gi
.ptr
, st
->st_gi
.len
);
1290 h
->hash_update(&hash_ctx
, st
->st_gr
.ptr
, st
->st_gr
.len
);
1291 h
->hash_final(st
->st_new_iv
, &hash_ctx
);
1294 /* Oakley Keying Material
1295 * Derived from Skeyid_e: if it is not big enough, generate more
1297 * See RFC 2409 "IKE" Appendix B
1300 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1301 const size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1302 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1303 u_char
*k
= st
->st_skeyid_e
.ptr
;
1305 if (keysize
> st
->st_skeyid_e
.len
)
1307 struct hmac_ctx ctx
;
1310 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_e
);
1311 hmac_update(&ctx
, "\0", 1);
1314 hmac_final(&keytemp
[i
], &ctx
);
1315 i
+= ctx
.hmac_digest_size
;
1319 hmac_update(&ctx
, &keytemp
[i
- ctx
.hmac_digest_size
], ctx
.hmac_digest_size
);
1323 clonereplacechunk(st
->st_enc_key
, k
, keysize
, "st_enc_key");
1327 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1328 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1329 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1330 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1331 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1332 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1336 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1337 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1338 * New Group Mode, or ISAKMP Informational Exchanges).
1339 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1340 * If hashus argument is TRUE, we're generating a hash for our end.
1341 * See RFC2409 IKE 5.
1343 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1344 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1345 * The extensive common logic is embodied in main_mode_hash_body().
1346 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1349 typedef void (*hash_update_t
)(union hash_ctx
*, const u_char
*, size_t) ;
1351 main_mode_hash_body(struct state
*st
1352 , bool hashi
/* Initiator? */
1353 , const pb_stream
*idpl
/* ID payload, as PBS */
1354 , union hash_ctx
*ctx
1355 , void (*hash_update_void
)(void *, const u_char
*input
, size_t))
1357 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1358 hash_update_t hash_update
=(hash_update_t
) hash_update_void
;
1359 #if 0 /* if desperate to debug hashing */
1360 # define hash_update(ctx, input, len) { \
1361 DBG_dump("hash input", input, len); \
1362 (hash_update)(ctx, input, len); \
1366 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1370 hash_update_chunk(ctx
, st
->st_gi
);
1371 hash_update_chunk(ctx
, st
->st_gr
);
1372 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1373 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1377 hash_update_chunk(ctx
, st
->st_gr
);
1378 hash_update_chunk(ctx
, st
->st_gi
);
1379 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1380 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1383 DBG(DBG_CRYPT
, DBG_log("hashing %lu bytes of SA"
1384 , (unsigned long) (st
->st_p1isa
.len
- sizeof(struct isakmp_generic
))));
1387 hash_update(ctx
, st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
)
1388 , st
->st_p1isa
.len
- sizeof(struct isakmp_generic
));
1390 /* Hash identification payload, without generic payload header.
1391 * We used to reconstruct ID Payload for this purpose, but now
1392 * we use the bytes as they appear on the wire to avoid
1393 * "spelling problems".
1396 , idpl
->start
+ sizeof(struct isakmp_generic
)
1397 , pbs_offset(idpl
) - sizeof(struct isakmp_generic
));
1399 # undef hash_update_chunk
1403 static size_t /* length of hash */
1404 main_mode_hash(struct state
*st
1405 , u_char
*hash_val
/* resulting bytes */
1406 , bool hashi
/* Initiator? */
1407 , const pb_stream
*idpl
) /* ID payload, as PBS; cur must be at end */
1409 struct hmac_ctx ctx
;
1411 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1412 main_mode_hash_body(st
, hashi
, idpl
, &ctx
.hash_ctx
, ctx
.h
->hash_update
);
1413 hmac_final(hash_val
, &ctx
);
1414 return ctx
.hmac_digest_size
;
1417 #if 0 /* only needed for DSS */
1419 main_mode_sha1(struct state
*st
1420 , u_char
*hash_val
/* resulting bytes */
1421 , size_t *hash_len
/* length of hash */
1422 , bool hashi
/* Initiator? */
1423 , const pb_stream
*idpl
) /* ID payload, as PBS */
1427 SHA1Init(&ctx
.ctx_sha1
);
1428 SHA1Update(&ctx
.ctx_sha1
, st
->st_skeyid
.ptr
, st
->st_skeyid
.len
);
1429 *hash_len
= SHA1_DIGEST_SIZE
;
1430 main_mode_hash_body(st
, hashi
, idpl
, &ctx
1431 , (void (*)(union hash_ctx
*, const u_char
*, unsigned int))&SHA1Update
);
1432 SHA1Final(hash_val
, &ctx
.ctx_sha1
);
1436 /* Create an RSA signature of a hash.
1437 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1438 * Use PKCS#1 version 1.5 encryption of hash (called
1439 * RSAES-PKCS1-V1_5) in PKCS#2.
1442 RSA_sign_hash(struct connection
*c
1443 , u_char sig_val
[RSA_MAX_OCTETS
]
1444 , const u_char
*hash_val
, size_t hash_len
)
1447 smartcard_t
*sc
= c
->spd
.this.sc
;
1449 if (sc
== NULL
) /* no smartcard */
1451 const struct RSA_private_key
*k
= get_RSA_private_key(c
);
1454 return 0; /* failure: no key to use */
1457 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1458 sign_hash(k
, hash_val
, hash_len
, sig_val
, sz
);
1460 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1462 lock_certs_and_keys("RSA_sign_hash");
1463 if (!scx_establish_context(sc
) || !scx_login(sc
))
1465 scx_release_context(sc
);
1466 unlock_certs_and_keys("RSA_sign_hash");
1470 sz
= scx_get_keylength(sc
);
1473 plog("failed to get keylength from smartcard");
1474 scx_release_context(sc
);
1475 unlock_certs_and_keys("RSA_sign_hash");
1479 DBG(DBG_CONTROL
| DBG_CRYPT
,
1480 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1481 , (int)sc
->slot
, sc
->id
)
1483 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1484 if (!pkcs11_keep_state
)
1485 scx_release_context(sc
);
1486 unlock_certs_and_keys("RSA_sign_hash");
1491 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1493 * As a side effect, on success, the public key is copied into the
1494 * state object to record the authenticator.
1496 * Can fail because wrong public key is used or because hash disagrees.
1497 * We distinguish because diagnostics should also.
1499 * The result is NULL if the Signature checked out.
1500 * Otherwise, the first character of the result indicates
1501 * how far along failure occurred. A greater character signifies
1505 * 0 reserved for caller
1506 * 1 SIG length doesn't match key length -- wrong key
1507 * 2-8 malformed ECB after decryption -- probably wrong key
1508 * 9 decrypted hash != computed hash -- probably correct key
1510 * Although the math should be the same for generating and checking signatures,
1511 * it is not: the knowledge of the private key allows more efficient (i.e.
1512 * different) computation for encryption.
1515 try_RSA_signature(const u_char hash_val
[MAX_DIGEST_LEN
], size_t hash_len
1516 , const pb_stream
*sig_pbs
, pubkey_t
*kr
1519 const u_char
*sig_val
= sig_pbs
->cur
;
1520 size_t sig_len
= pbs_left(sig_pbs
);
1521 u_char s
[RSA_MAX_OCTETS
]; /* for decrypted sig_val */
1522 u_char
*hash_in_s
= &s
[sig_len
- hash_len
];
1523 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1525 /* decrypt the signature -- reversing RSA_sign_hash */
1526 if (sig_len
!= k
->k
)
1528 /* XXX notification: INVALID_KEY_INFORMATION */
1529 return "1" "SIG length does not match public key length";
1532 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1537 n_to_mpz(c
, sig_val
, sig_len
);
1538 mpz_powm(c
, c
, &k
->e
, &k
->n
);
1540 temp_s
= mpz_to_n(c
, sig_len
); /* back to octets */
1541 memcpy(s
, temp_s
.ptr
, sig_len
);
1546 /* sanity check on signature: see if it matches
1547 * PKCS#1 v1.5 8.1 encryption-block formatting
1553 ugh
= "2" "no leading 00";
1554 else if (hash_in_s
[-1] != 0x00)
1555 ugh
= "3" "00 separator not present";
1556 else if (s
[1] == 0x01)
1560 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1564 ugh
= "4" "invalid Padding String";
1569 else if (s
[1] == 0x02)
1573 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1577 ugh
= "5" "invalid Padding String";
1583 ugh
= "6" "Block Type not 01 or 02";
1587 /* note: it might be a good idea to make sure that
1588 * an observer cannot tell what kind of failure happened.
1589 * I don't know what this means in practice.
1591 /* We probably selected the wrong public key for peer:
1592 * SIG Payload decrypted into malformed ECB
1594 /* XXX notification: INVALID_KEY_INFORMATION */
1599 /* We have the decoded hash: see if it matches. */
1600 if (memcmp(hash_val
, hash_in_s
, hash_len
) != 0)
1602 /* good: header, hash, signature, and other payloads well-formed
1603 * good: we could find an RSA Sig key for the peer.
1604 * bad: hash doesn't match
1605 * Guess: sides disagree about key to be used.
1607 DBG_cond_dump(DBG_CRYPT
, "decrypted SIG", s
, sig_len
);
1608 DBG_cond_dump(DBG_CRYPT
, "computed HASH", hash_val
, hash_len
);
1609 /* XXX notification: INVALID_HASH_INFORMATION */
1610 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1613 /* Success: copy successful key into state.
1614 * There might be an old one if we previously aborted this
1617 unreference_key(&st
->st_peer_pubkey
);
1618 st
->st_peer_pubkey
= reference_key(kr
);
1620 return NULL
; /* happy happy */
1623 /* Check signature against all RSA public keys we can find.
1624 * If we need keys from DNS KEY records, and they haven't been fetched,
1625 * return STF_SUSPEND to ask for asynch DNS lookup.
1627 * Note: parameter keys_from_dns contains results of DNS lookup for key
1628 * or is NULL indicating lookup not yet tried.
1630 * take_a_crack is a helper function. Mostly forensic.
1631 * If only we had coroutines.
1634 /* RSA_check_signature's args that take_a_crack needs */
1636 const u_char
*hash_val
;
1638 const pb_stream
*sig_pbs
;
1640 /* state carried between calls */
1641 err_t best_ugh
; /* most successful failure */
1642 int tried_cnt
; /* number of keys tried */
1643 char tried
[50]; /* keyids of tried public keys */
1644 char *tn
; /* roof of tried[] */
1648 take_a_crack(struct tac_state
*s
1650 , const char *story USED_BY_DEBUG
)
1652 err_t ugh
= try_RSA_signature(s
->hash_val
, s
->hash_len
, s
->sig_pbs
1654 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1659 DBG(DBG_CRYPT
| DBG_CONTROL
1660 , DBG_log("an RSA Sig check passed with *%s [%s]"
1661 , k
->keyid
, story
));
1667 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1668 , ugh
+ 1, k
->keyid
, story
));
1669 if (s
->best_ugh
== NULL
|| s
->best_ugh
[0] < ugh
[0])
1672 && s
->tn
- s
->tried
+ KEYID_BUF
+ 2 < (ptrdiff_t)sizeof(s
->tried
))
1674 strcpy(s
->tn
, " *");
1675 strcpy(s
->tn
+ 2, k
->keyid
);
1676 s
->tn
+= strlen(s
->tn
);
1683 RSA_check_signature(const struct id
* peer
1685 , const u_char hash_val
[MAX_DIGEST_LEN
]
1687 , const pb_stream
*sig_pbs
1689 , const pubkey_list_t
*keys_from_dns
1690 #endif /* USE_KEYRR */
1691 , const struct gw_info
*gateways_from_dns
1694 const struct connection
*c
= st
->st_connection
;
1696 err_t dns_ugh
= NULL
;
1699 s
.hash_val
= hash_val
;
1700 s
.hash_len
= hash_len
;
1701 s
.sig_pbs
= sig_pbs
;
1707 /* try all gateway records hung off c */
1708 if (c
->policy
& POLICY_OPPO
)
1712 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1714 /* only consider entries that have a key and are for our peer */
1715 if (gw
->gw_key_present
1716 && same_id(&gw
->gw_id
, &c
->spd
.that
.id
)
1717 && take_a_crack(&s
, gw
->key
, "key saved from DNS TXT"))
1722 /* try all appropriate Public keys */
1724 pubkey_list_t
*p
, **pp
;
1728 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1730 pubkey_t
*key
= p
->key
;
1732 if (key
->alg
== PUBKEY_ALG_RSA
&& same_id(peer
, &key
->id
))
1734 time_t now
= time(NULL
);
1736 /* check if found public key has expired */
1737 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1739 loglog(RC_LOG_SERIOUS
,
1740 "cached RSA public key has expired and has been deleted");
1741 *pp
= free_public_keyentry(p
);
1742 continue; /* continue with next public key */
1745 if (take_a_crack(&s
, key
, "preloaded key"))
1752 /* if no key was found (evidenced by best_ugh == NULL)
1753 * and that side of connection is key_from_DNS_on_demand
1754 * then go search DNS for keys for peer.
1756 if (s
.best_ugh
== NULL
&& c
->spd
.that
.key_from_DNS_on_demand
)
1758 if (gateways_from_dns
!= NULL
)
1761 const struct gw_info
*gwp
;
1763 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1764 if (gwp
->gw_key_present
1765 && take_a_crack(&s
, gwp
->key
, "key from DNS TXT"))
1769 else if (keys_from_dns
!= NULL
)
1772 const pubkey_list_t
*kr
;
1774 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1775 if (kr
->key
->alg
== PUBKEY_ALG_RSA
1776 && take_a_crack(&s
, kr
->key
, "key from DNS KEY"))
1779 #endif /* USE_KEYRR */
1782 /* nothing yet: ask for asynch DNS lookup */
1787 /* no acceptable key was found: diagnose */
1789 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1791 (void) idtoa(peer
, id_buf
, sizeof(id_buf
));
1793 if (s
.best_ugh
== NULL
)
1795 if (dns_ugh
== NULL
)
1796 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1799 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1800 "; DNS search for KEY failed (%s)"
1803 /* ??? is this the best code there is? */
1804 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1807 if (s
.best_ugh
[0] == '9')
1809 loglog(RC_LOG_SERIOUS
, "%s", s
.best_ugh
+ 1);
1810 /* XXX Could send notification back */
1811 return STF_FAIL
+ INVALID_HASH_INFORMATION
;
1815 if (s
.tried_cnt
== 1)
1817 loglog(RC_LOG_SERIOUS
1818 , "Signature check (on %s) failed (wrong key?); tried%s"
1821 DBG_log("public key for %s failed:"
1822 " decrypted SIG payload into a malformed ECB (%s)"
1823 , id_buf
, s
.best_ugh
+ 1));
1827 loglog(RC_LOG_SERIOUS
1828 , "Signature check (on %s) failed:"
1829 " tried%s keys but none worked."
1832 DBG_log("all %d public keys for %s failed:"
1833 " best decrypted SIG payload into a malformed ECB (%s)"
1834 , s
.tried_cnt
, id_buf
, s
.best_ugh
+ 1));
1836 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1841 static notification_t
1842 accept_nonce(struct msg_digest
*md
, chunk_t
*dest
, const char *name
)
1844 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1845 size_t len
= pbs_left(nonce_pbs
);
1847 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1849 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1850 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1851 return PAYLOAD_MALFORMED
; /* ??? */
1853 clonereplacechunk(*dest
, nonce_pbs
->cur
, len
, "nonce");
1854 return NOTHING_WRONG
;
1857 /* encrypt message, sans fixed part of header
1858 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1859 * The theory is that there will be no "backing out", so we commit to IV.
1860 * We also close the pbs.
1863 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1865 const struct encrypt_desc
*e
= st
->st_oakley
.encrypter
;
1866 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1867 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1869 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1871 /* Pad up to multiple of encryption blocksize.
1872 * See the description associated with the definition of
1873 * struct isakmp_hdr in packet.h.
1876 size_t padding
= pad_up(enc_len
, e
->enc_blocksize
);
1880 if (!out_zero(padding
, pbs
, "encryption padding"))
1886 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1888 /* e->crypt(TRUE, enc_start, enc_len, st); */
1889 crypto_cbc_encrypt(e
, TRUE
, enc_start
, enc_len
, st
);
1892 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1897 /* Compute HASH(1), HASH(2) of Quick Mode.
1898 * HASH(1) is part of Quick I1 message.
1899 * HASH(2) is part of Quick R1 message.
1900 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1901 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1904 quick_mode_hash12(u_char
*dest
, const u_char
*start
, const u_char
*roof
1905 , const struct state
*st
, const msgid_t
*msgid
, bool hash2
)
1907 struct hmac_ctx ctx
;
1909 #if 0 /* if desperate to debug hashing */
1910 # define hmac_update(ctx, ptr, len) { \
1911 DBG_dump("hash input", (ptr), (len)); \
1912 (hmac_update)((ctx), (ptr), (len)); \
1914 DBG_dump("hash key", st
->st_skeyid_a
.ptr
, st
->st_skeyid_a
.len
);
1916 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1917 hmac_update(&ctx
, (const void *) msgid
, sizeof(msgid_t
));
1919 hmac_update_chunk(&ctx
, st
->st_ni
); /* include Ni_b in the hash */
1920 hmac_update(&ctx
, start
, roof
-start
);
1921 hmac_final(dest
, &ctx
);
1924 DBG_log("HASH(%d) computed:", hash2
+ 1);
1925 DBG_dump("", dest
, ctx
.hmac_digest_size
));
1926 return ctx
.hmac_digest_size
;
1930 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1931 * Used by: quick_inR1_outI2, quick_inI2
1932 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1933 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1934 * Message ID and Nonces. This is a mistake.
1937 quick_mode_hash3(u_char
*dest
, struct state
*st
)
1939 struct hmac_ctx ctx
;
1941 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1942 hmac_update(&ctx
, "\0", 1);
1943 hmac_update(&ctx
, (u_char
*) &st
->st_msgid
, sizeof(st
->st_msgid
));
1944 hmac_update_chunk(&ctx
, st
->st_ni
);
1945 hmac_update_chunk(&ctx
, st
->st_nr
);
1946 hmac_final(dest
, &ctx
);
1947 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, ctx
.hmac_digest_size
);
1948 return ctx
.hmac_digest_size
;
1951 /* Compute Phase 2 IV.
1952 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1955 init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1957 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1960 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:"
1961 , st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1963 st
->st_new_iv_len
= h
->hash_digest_size
;
1964 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1967 h
->hash_update(&ctx
, st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1968 passert(*msgid
!= 0);
1969 h
->hash_update(&ctx
, (const u_char
*)msgid
, sizeof(*msgid
));
1970 h
->hash_final(st
->st_new_iv
, &ctx
);
1972 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:"
1973 , st
->st_new_iv
, st
->st_new_iv_len
);
1976 /* Initiate quick mode.
1977 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1978 * (see RFC 2409 "IKE" 5.5)
1979 * Note: this is not called from demux.c
1983 emit_subnet_id(ip_subnet
*net
1984 , u_int8_t np
, u_int8_t protoid
, u_int16_t port
, pb_stream
*outs
)
1986 struct isakmp_ipsec_id id
;
1989 const unsigned char *tbp
;
1993 id
.isaiid_idtype
= subnetishost(net
)
1994 ?
aftoinfo(subnettypeof(net
))->id_addr
1995 : aftoinfo(subnettypeof(net
))->id_subnet
;
1996 id
.isaiid_protoid
= protoid
;
1997 id
.isaiid_port
= port
;
1999 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
2002 networkof(net
, &ta
);
2003 tal
= addrbytesptr(&ta
, &tbp
);
2004 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
2007 if (!subnetishost(net
))
2010 tal
= addrbytesptr(&ta
, &tbp
);
2011 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
2015 close_output_pbs(&id_pbs
);
2020 quick_outI1(int whack_sock
2021 , struct state
*isakmp_sa
2022 , struct connection
*c
2025 , so_serial_t replacing
)
2027 struct state
*st
= duplicate_state(isakmp_sa
);
2028 pb_stream reply
; /* not really a reply */
2030 u_char
/* set by START_HASH_PAYLOAD: */
2031 *r_hashval
, /* where in reply to jam hash value */
2032 *r_hash_start
; /* start of what is to be hashed */
2033 bool has_client
= c
->spd
.this.has_client
|| c
->spd
.that
.has_client
||
2034 c
->spd
.this.protocol
|| c
->spd
.that
.protocol
||
2035 c
->spd
.this.port
|| c
->spd
.that
.port
;
2037 bool send_natoa
= FALSE
;
2038 u_int8_t np
= ISAKMP_NEXT_NONE
;
2040 st
->st_whack_sock
= whack_sock
;
2041 st
->st_connection
= c
;
2042 set_cur_state(st
); /* we must reset before exit */
2043 st
->st_policy
= policy
;
2046 st
->st_myuserprotoid
= c
->spd
.this.protocol
;
2047 st
->st_peeruserprotoid
= c
->spd
.that
.protocol
;
2048 st
->st_myuserport
= c
->spd
.this.port
;
2049 st
->st_peeruserport
= c
->spd
.that
.port
;
2051 st
->st_msgid
= generate_msgid(isakmp_sa
);
2052 st
->st_state
= STATE_QUICK_I1
;
2054 insert_state(st
); /* needs cookies, connection, and msgid */
2056 if (replacing
== SOS_NOBODY
)
2057 plog("initiating Quick Mode %s {using isakmp#%lu}"
2058 , prettypolicy(policy
)
2059 , isakmp_sa
->st_serialno
);
2061 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2062 , prettypolicy(policy
)
2064 , isakmp_sa
->st_serialno
);
2066 if (isakmp_sa
->nat_traversal
& NAT_T_DETECTED
)
2068 /* Duplicate nat_traversal status in new state */
2069 st
->nat_traversal
= isakmp_sa
->nat_traversal
;
2071 if (isakmp_sa
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
))
2074 nat_traversal_change_port_lookup(NULL
, st
);
2077 st
->nat_traversal
= 0;
2079 /* are we going to send a NAT-OA payload? */
2080 if ((st
->nat_traversal
& NAT_T_WITH_NATOA
)
2081 && !(st
->st_policy
& POLICY_TUNNEL
)
2082 && (st
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
)))
2085 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
2086 ISAKMP_NEXT_NATOA_RFC
: ISAKMP_NEXT_NATOA_DRAFTS
;
2090 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
2094 struct isakmp_hdr hdr
;
2096 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
2097 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
2098 hdr
.isa_xchg
= ISAKMP_XCHG_QUICK
;
2099 hdr
.isa_msgid
= st
->st_msgid
;
2100 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
2101 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
2102 memcpy(hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
2103 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
2106 return STF_INTERNAL_ERROR
;
2110 /* HASH(1) -- create and note space to be filled later */
2111 START_HASH_PAYLOAD(rbody
, ISAKMP_NEXT_SA
);
2116 * See if pfs_group has been specified for this conn,
2117 * if not, fallback to old use-same-as-P1 behaviour
2120 if (st
->st_connection
)
2121 st
->st_pfs_group
= ike_alg_pfsgroup(st
->st_connection
, policy
);
2122 if (!st
->st_pfs_group
)
2124 /* If PFS specified, use the same group as during Phase 1:
2125 * since no negotiation is possible, we pick one that is
2126 * very likely supported.
2128 st
->st_pfs_group
= policy
& POLICY_PFS? isakmp_sa
->st_oakley
.group
: NULL
;
2130 /* Emit SA payload based on a subset of the policy bits.
2131 * POLICY_COMPRESS is considered iff we can do IPcomp.
2134 lset_t pm
= POLICY_ENCRYPT
| POLICY_AUTHENTICATE
;
2137 pm
|= POLICY_COMPRESS
;
2140 , &ipsec_sadb
[(st
->st_policy
& pm
) >> POLICY_IPSEC_SHIFT
]
2141 , st
, FALSE
, ISAKMP_NEXT_NONCE
))
2144 return STF_INTERNAL_ERROR
;
2149 if (!build_and_ship_nonce(&st
->st_ni
, &rbody
2150 , policy
& POLICY_PFS? ISAKMP_NEXT_KE
: has_client? ISAKMP_NEXT_ID
: np
2154 return STF_INTERNAL_ERROR
;
2157 /* [ KE ] out (for PFS) */
2159 if (st
->st_pfs_group
!= NULL
)
2161 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_pfs_group
2162 , &rbody
, has_client? ISAKMP_NEXT_ID
: np
))
2165 return STF_INTERNAL_ERROR
;
2169 /* [ IDci, IDcr ] out */
2172 /* IDci (we are initiator), then IDcr (peer is responder) */
2173 if (!emit_subnet_id(&c
->spd
.this.client
2174 , ISAKMP_NEXT_ID
, st
->st_myuserprotoid
, st
->st_myuserport
, &rbody
)
2175 || !emit_subnet_id(&c
->spd
.that
.client
2176 , np
, st
->st_peeruserprotoid
, st
->st_peeruserport
, &rbody
))
2179 return STF_INTERNAL_ERROR
;
2183 /* Send NAT-OA if our address is NATed */
2186 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE
, &rbody
, st
))
2189 return STF_INTERNAL_ERROR
;
2193 /* finish computing HASH(1), inserting it in output */
2194 (void) quick_mode_hash12(r_hashval
, r_hash_start
, rbody
.cur
2195 , st
, &st
->st_msgid
, FALSE
);
2197 /* encrypt message, except for fixed part of header */
2199 init_phase2_iv(isakmp_sa
, &st
->st_msgid
);
2200 st
->st_new_iv_len
= isakmp_sa
->st_new_iv_len
;
2201 memcpy(st
->st_new_iv
, isakmp_sa
->st_new_iv
, st
->st_new_iv_len
);
2203 if (!encrypt_message(&rbody
, st
))
2206 return STF_INTERNAL_ERROR
;
2209 /* save packet, now that we know its size */
2210 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
2211 , "reply packet from quick_outI1");
2213 /* send the packet */
2215 send_packet(st
, "quick_outI1");
2218 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
2220 if (replacing
== SOS_NOBODY
)
2221 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2223 , enum_name(&state_names
, st
->st_state
));
2225 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2226 , "%s: initiate to replace #%lu"
2227 , enum_name(&state_names
, st
->st_state
)
2235 * Decode the CERT payload of Phase 1.
2238 decode_cert(struct msg_digest
*md
)
2240 struct payload_digest
*p
;
2242 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2244 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2247 blob
.ptr
= p
->pbs
.cur
;
2248 blob
.len
= pbs_left(&p
->pbs
);
2249 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2251 x509cert_t cert
= empty_x509cert
;
2252 if (parse_x509cert(blob
, 0, &cert
))
2254 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2257 DBG_log("Public key validated")
2259 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2263 plog("X.509 certificate rejected");
2265 free_generalNames(cert
.subjectAltName
, FALSE
);
2266 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2269 plog("Syntax error in X.509 certificate");
2271 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2273 x509cert_t
*cert
= NULL
;
2275 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2276 store_x509certs(&cert
, strict_crl_policy
);
2278 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2282 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2283 enum_show(&cert_type_names
, cert
->isacert_type
));
2284 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2290 * Decode the CR payload of Phase 1.
2293 decode_cr(struct msg_digest
*md
, struct connection
*c
)
2295 struct payload_digest
*p
;
2297 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2299 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2302 ca_name
.len
= pbs_left(&p
->pbs
);
2303 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2305 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2307 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2311 if (ca_name
.len
> 0)
2315 if (!is_asn1(ca_name
))
2318 gn
= alloc_thing(generalName_t
, "generalName");
2319 clonetochunk(ca_name
, ca_name
.ptr
,ca_name
.len
, "ca name");
2320 gn
->kind
= GN_DIRECTORY_NAME
;
2322 gn
->next
= c
->requested_ca
;
2323 c
->requested_ca
= gn
;
2325 c
->got_certrequest
= TRUE
;
2327 DBG(DBG_PARSING
| DBG_CONTROL
,
2328 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2329 DBG_log("requested CA: '%s'", buf
);
2333 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2334 enum_show(&cert_type_names
, cr
->isacr_type
));
2338 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2339 * Note: we may change connections as a result.
2340 * We must be called before SIG or HASH are decoded since we
2341 * may change the peer's RSA key or ID.
2344 decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2346 struct state
*const st
= md
->st
;
2347 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2348 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2349 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2351 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2352 * It talks about the protocol ID and Port fields of the ID
2353 * Payload, but they don't exist as such in Phase 1.
2354 * We use more appropriate names.
2355 * isaid_doi_specific_a is in place of Protocol ID.
2356 * isaid_doi_specific_b is in place of Port.
2357 * Besides, there is no good reason for allowing these to be
2358 * other than 0 in Phase 1.
2360 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2361 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2362 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2364 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2365 "accepted with port_floating NAT-T",
2366 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2368 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2369 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2371 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2373 , IPPROTO_UDP
, IKE_UDP_PORT
2374 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2378 peer
->kind
= id
->isaid_idtype
;
2384 /* failure mode for initaddr is probably inappropriate address length */
2386 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2387 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2392 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2393 , enum_show(&ident_names
, peer
->kind
), ugh
);
2394 /* XXX Could send notification back */
2401 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2403 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2408 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2410 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2411 , enum_show(&ident_names
, peer
->kind
));
2415 /* ??? ought to do some more sanity check, but what? */
2417 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2421 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2423 DBG_dump_chunk("KEY ID:", peer
->name
));
2426 case ID_DER_ASN1_DN
:
2427 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2429 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2433 /* XXX Could send notification back */
2434 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2435 , enum_show(&ident_names
, peer
->kind
));
2442 idtoa(peer
, buf
, sizeof(buf
));
2443 plog("Peer ID is %s: '%s'",
2444 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2447 /* check for certificates */
2452 /* Now that we've decoded the ID payload, let's see if we
2453 * need to switch connections.
2454 * We must not switch horses if we initiated:
2455 * - if the initiation was explicit, we'd be ignoring user's intent
2456 * - if opportunistic, we'll lose our HOLD info
2459 switch_connection(struct msg_digest
*md
, struct id
*peer
, bool initiator
)
2461 struct state
*const st
= md
->st
;
2462 struct connection
*c
= st
->st_connection
;
2464 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2465 ? st
->st_peer_pubkey
->issuer
: empty_chunk
;
2470 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2471 DBG_log("peer CA: '%s'", buf
);
2478 if (!same_id(&c
->spd
.that
.id
, peer
))
2480 char expect
[BUF_LEN
]
2483 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2484 idtoa(peer
, found
, sizeof(found
));
2485 loglog(RC_LOG_SERIOUS
2486 , "we require peer to have ID '%s', but peer declares '%s'"
2494 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.that
.ca
, "%none");
2495 DBG_log("required CA: '%s'", buf
);
2498 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2500 loglog(RC_LOG_SERIOUS
2501 , "we don't accept the peer's CA");
2507 struct connection
*r
;
2509 /* check for certificate requests */
2512 r
= refine_host_connection(st
, peer
, peer_ca
);
2514 /* delete the collected certificate requests */
2515 free_generalNames(c
->requested_ca
, TRUE
);
2516 c
->requested_ca
= NULL
;
2522 idtoa(peer
, buf
, sizeof(buf
));
2523 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2530 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2531 DBG_log("offered CA: '%s'", buf
);
2536 /* apparently, r is an improvement on c -- replace */
2539 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2540 if (r
->kind
== CK_TEMPLATE
)
2542 /* instantiate it, filling in peer's ID */
2543 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2544 , c
->spd
.that
.host_port
, NULL
, peer
);
2547 /* copy certificate request info */
2548 r
->got_certrequest
= c
->got_certrequest
;
2550 st
->st_connection
= r
; /* kill reference to c */
2551 set_cur_connection(r
);
2552 connection_discard(c
);
2554 else if (c
->spd
.that
.has_id_wildcards
)
2556 free_id_content(&c
->spd
.that
.id
);
2557 c
->spd
.that
.id
= *peer
;
2558 c
->spd
.that
.has_id_wildcards
= FALSE
;
2559 unshare_id_content(&c
->spd
.that
.id
);
2565 /* Decode the variable part of an ID packet (during Quick Mode).
2566 * This is designed for packets that identify clients, not peers.
2567 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2568 * (1) it is wrong and (2) we use this value for inband signalling.
2571 decode_net_id(struct isakmp_ipsec_id
*id
2574 , const char *which
)
2576 const struct af_info
*afi
= NULL
;
2578 /* Note: the following may be a pointer into static memory
2579 * that may be recycled, but only if the type is not known.
2580 * That case is disposed of very early -- in the first switch.
2582 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2584 switch (id
->isaiid_idtype
)
2587 case ID_IPV4_ADDR_SUBNET
:
2588 case ID_IPV4_ADDR_RANGE
:
2589 afi
= &af_inet4_info
;
2592 case ID_IPV6_ADDR_SUBNET
:
2593 case ID_IPV6_ADDR_RANGE
:
2594 afi
= &af_inet6_info
;
2599 /* XXX support more */
2600 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2602 /* XXX Could send notification back */
2606 switch (id
->isaiid_idtype
)
2611 ip_address temp_address
;
2614 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2618 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2619 , which
, idtypename
, ugh
);
2620 /* XXX Could send notification back */
2623 if (isanyaddr(&temp_address
))
2625 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2626 , which
, idtypename
, ip_str(&temp_address
));
2627 /* XXX Could send notification back */
2630 happy(addrtosubnet(&temp_address
, net
));
2631 DBG(DBG_PARSING
| DBG_CONTROL
2632 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2636 case ID_IPV4_ADDR_SUBNET
:
2637 case ID_IPV6_ADDR_SUBNET
:
2639 ip_address temp_address
, temp_mask
;
2642 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2644 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2645 , which
, idtypename
);
2646 /* XXX Could send notification back */
2649 ugh
= initaddr(id_pbs
->cur
2650 , afi
->ia_sz
, afi
->af
, &temp_address
);
2652 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2653 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2655 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2657 if (ugh
== NULL
&& subnetisnone(net
))
2658 ugh
= "contains only anyaddr";
2661 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2662 , which
, idtypename
, ugh
);
2663 /* XXX Could send notification back */
2666 DBG(DBG_PARSING
| DBG_CONTROL
,
2668 char temp_buff
[SUBNETTOT_BUF
];
2670 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2671 DBG_log("%s is subnet %s", which
, temp_buff
);
2676 case ID_IPV4_ADDR_RANGE
:
2677 case ID_IPV6_ADDR_RANGE
:
2679 ip_address temp_address_from
, temp_address_to
;
2682 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2684 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2685 , which
, idtypename
);
2686 /* XXX Could send notification back */
2689 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2691 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2692 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2695 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2696 , which
, idtypename
, ugh
);
2697 /* XXX Could send notification back */
2701 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2702 if (ugh
== NULL
&& subnetisnone(net
))
2703 ugh
= "contains only anyaddr";
2706 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2708 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2709 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2710 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2711 " %s - %s unacceptable: %s"
2712 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2715 DBG(DBG_PARSING
| DBG_CONTROL
,
2717 char temp_buff
[SUBNETTOT_BUF
];
2719 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2720 DBG_log("%s is subnet %s (received as range)"
2721 , which
, temp_buff
);
2727 /* set the port selector */
2728 setportof(htons(id
->isaiid_port
), &net
->addr
);
2730 DBG(DBG_PARSING
| DBG_CONTROL
,
2731 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2737 /* like decode, but checks that what is received matches what was sent */
2740 check_net_id(struct isakmp_ipsec_id
*id
2745 , const char *which
)
2749 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2752 if (!samesubnet(net
, &net_temp
)
2753 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2755 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2762 * look for the existence of a non-expiring preloaded public key
2765 has_preloaded_public_key(struct state
*st
)
2767 struct connection
*c
= st
->st_connection
;
2769 /* do not consider rw connections since
2770 * the peer's identity must be known
2772 if (c
->kind
== CK_PERMANENT
)
2776 /* look for a matching RSA public key */
2777 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2779 pubkey_t
*key
= p
->key
;
2781 if (key
->alg
== PUBKEY_ALG_RSA
&&
2782 same_id(&c
->spd
.that
.id
, &key
->id
) &&
2783 key
->until_time
== UNDEFINED_TIME
)
2785 /* found a preloaded public key */
2794 * Produce the new key material of Quick Mode.
2795 * RFC 2409 "IKE" section 5.5
2796 * specifies how this is to be done.
2799 compute_proto_keymat(struct state
*st
2801 , struct ipsec_proto_info
*pi
)
2803 size_t needed_len
; /* bytes of keying material needed */
2805 /* Add up the requirements for keying material
2806 * (It probably doesn't matter if we produce too much!)
2810 case PROTO_IPSEC_ESP
:
2811 switch (pi
->attrs
.transid
)
2817 needed_len
= DES_CBC_BLOCK_SIZE
;
2820 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2823 #ifndef NO_KERNEL_ALG
2824 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2825 /* XXX: check key_len "coupling with kernel.c's */
2826 if (pi
->attrs
.key_len
) {
2827 needed_len
=pi
->attrs
.key_len
/8;
2828 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2829 "key_len=%d from peer",
2835 bad_case(pi
->attrs
.transid
);
2838 #ifndef NO_KERNEL_ALG
2839 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2840 "needed_len (after ESP enc)=%d",
2842 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2843 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2846 switch (pi
->attrs
.auth
)
2848 case AUTH_ALGORITHM_NONE
:
2850 case AUTH_ALGORITHM_HMAC_MD5
:
2851 needed_len
+= HMAC_MD5_KEY_LEN
;
2853 case AUTH_ALGORITHM_HMAC_SHA1
:
2854 needed_len
+= HMAC_SHA1_KEY_LEN
;
2856 case AUTH_ALGORITHM_DES_MAC
:
2858 bad_case(pi
->attrs
.auth
);
2860 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2861 "needed_len (after ESP auth)=%d",
2865 case PROTO_IPSEC_AH
:
2866 switch (pi
->attrs
.transid
)
2869 needed_len
= HMAC_MD5_KEY_LEN
;
2872 needed_len
= HMAC_SHA1_KEY_LEN
;
2875 bad_case(pi
->attrs
.transid
);
2883 pi
->keymat_len
= needed_len
;
2885 /* Allocate space for the keying material.
2886 * Although only needed_len bytes are desired, we
2887 * must round up to a multiple of ctx.hmac_digest_size
2888 * so that our buffer isn't overrun.
2891 struct hmac_ctx ctx_me
, ctx_peer
;
2892 size_t needed_space
; /* space needed for keying material (rounded up) */
2895 hmac_init_chunk(&ctx_me
, st
->st_oakley
.hasher
, st
->st_skeyid_d
);
2896 ctx_peer
= ctx_me
; /* duplicate initial conditions */
2898 needed_space
= needed_len
+ pad_up(needed_len
, ctx_me
.hmac_digest_size
);
2899 replace(pi
->our_keymat
, alloc_bytes(needed_space
, "keymat in compute_keymat()"));
2900 replace(pi
->peer_keymat
, alloc_bytes(needed_space
, "peer_keymat in quick_inI1_outR1()"));
2904 if (st
->st_shared
.ptr
!= NULL
)
2906 /* PFS: include the g^xy */
2907 hmac_update_chunk(&ctx_me
, st
->st_shared
);
2908 hmac_update_chunk(&ctx_peer
, st
->st_shared
);
2910 hmac_update(&ctx_me
, &protoid
, sizeof(protoid
));
2911 hmac_update(&ctx_peer
, &protoid
, sizeof(protoid
));
2913 hmac_update(&ctx_me
, (u_char
*)&pi
->our_spi
, sizeof(pi
->our_spi
));
2914 hmac_update(&ctx_peer
, (u_char
*)&pi
->attrs
.spi
, sizeof(pi
->attrs
.spi
));
2916 hmac_update_chunk(&ctx_me
, st
->st_ni
);
2917 hmac_update_chunk(&ctx_peer
, st
->st_ni
);
2919 hmac_update_chunk(&ctx_me
, st
->st_nr
);
2920 hmac_update_chunk(&ctx_peer
, st
->st_nr
);
2922 hmac_final(pi
->our_keymat
+ i
, &ctx_me
);
2923 hmac_final(pi
->peer_keymat
+ i
, &ctx_peer
);
2925 i
+= ctx_me
.hmac_digest_size
;
2926 if (i
>= needed_space
)
2929 /* more keying material needed: prepare to go around again */
2931 hmac_reinit(&ctx_me
);
2932 hmac_reinit(&ctx_peer
);
2934 hmac_update(&ctx_me
, pi
->our_keymat
+ i
- ctx_me
.hmac_digest_size
2935 , ctx_me
.hmac_digest_size
);
2936 hmac_update(&ctx_peer
, pi
->peer_keymat
+ i
- ctx_peer
.hmac_digest_size
2937 , ctx_peer
.hmac_digest_size
);
2942 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2943 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2947 compute_keymats(struct state
*st
)
2949 if (st
->st_ah
.present
)
2950 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2951 if (st
->st_esp
.present
)
2952 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2955 /* State Transition Functions.
2957 * The definition of state_microcode_table in demux.c is a good
2958 * overview of these routines.
2960 * - Called from process_packet; result handled by complete_state_transition
2961 * - struct state_microcode member "processor" points to these
2962 * - these routine definitionss are in state order
2963 * - these routines must be restartable from any point of error return:
2964 * beware of memory allocated before any error.
2965 * - output HDR is usually emitted by process_packet (if state_microcode
2966 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2968 * The transition functions' functions include:
2969 * - process and judge payloads
2970 * - update st_iv (result of decryption is in st_new_iv)
2971 * - build reply packet
2974 /* Handle a Main Mode Oakley first packet (responder side).
2978 main_inI1_outR1(struct msg_digest
*md
)
2980 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2982 struct connection
*c
;
2983 struct isakmp_proposal proposal
;
2984 pb_stream proposal_pbs
;
2986 u_int32_t ipsecdoisit
;
2987 lset_t policy
= LEMPTY
;
2988 int vids_to_send
= 0;
2990 /* We preparse the peer's proposal in order to determine
2991 * the requested authentication policy (RSA or PSK)
2993 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2994 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2996 backup_pbs(&proposal_pbs
);
2997 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2998 , proposal
.isap_notrans
, &policy
));
2999 restore_pbs(&proposal_pbs
);
3001 /* We are only considering candidate connections that match
3002 * the requested authentication policy (RSA or PSK)
3004 c
= find_host_connection(&md
->iface
->addr
, pluto_port
3005 , &md
->sender
, md
->sender_port
, policy
);
3007 if (c
== NULL
&& md
->iface
->ike_float
)
3009 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
3010 , &md
->sender
, md
->sender_port
, policy
);
3015 /* See if a wildcarded connection can be found.
3016 * We cannot pick the right connection, so we're making a guess.
3017 * All Road Warrior connections are fair game:
3018 * we pick the first we come across (if any).
3019 * If we don't find any, we pick the first opportunistic
3020 * with the smallest subnet that includes the peer.
3021 * There is, of course, no necessary relationship between
3022 * an Initiator's address and that of its client,
3023 * but Food Groups kind of assumes one.
3026 struct connection
*d
;
3028 d
= find_host_connection(&md
->iface
->addr
3029 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
3031 for (; d
!= NULL
; d
= d
->hp_next
)
3033 if (d
->kind
== CK_GROUP
)
3039 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
3041 /* must be Road Warrior: we have a winner */
3046 /* Opportunistic or Shunt: pick tightest match */
3047 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
3048 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
3056 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3057 " but no connection has been authorized%s%s"
3058 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
3059 , (policy
!= LEMPTY
) ?
" with policy=" : ""
3060 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
3061 /* XXX notification is in order! */
3064 else if (c
->kind
!= CK_TEMPLATE
)
3066 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3067 " but \"%s\" forbids connection"
3068 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
3069 /* XXX notification is in order! */
3074 /* Create a temporary connection that is a copy of this one.
3075 * His ID isn't declared yet.
3077 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
3080 else if (c
->kind
== CK_TEMPLATE
)
3082 /* Create an instance
3083 * This is a rare case: wildcard peer ID but static peer IP address
3085 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
3089 md
->st
= st
= new_state();
3090 st
->st_connection
= c
;
3091 set_cur_state(st
); /* (caller will reset cur_state) */
3092 st
->st_try
= 0; /* not our job to try again from start */
3093 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
3095 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
3096 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
3098 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3100 st
->st_doi
= ISAKMP_DOI_IPSEC
;
3101 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
3103 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
3105 plog("responding to Main Mode from unknown peer %s:%u"
3106 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
3108 else if (c
->kind
== CK_INSTANCE
)
3110 plog("responding to Main Mode from unknown peer %s"
3111 , ip_str(&c
->spd
.that
.host_addr
));
3115 plog("responding to Main Mode");
3118 /* parse_isakmp_sa also spits out a winning SA into our reply,
3119 * so we have to build our md->reply and emit HDR before calling it.
3122 /* determine how many Vendor ID payloads we will be sending */
3125 if (SEND_CISCO_UNITY_VID
)
3131 /* always send DPD Vendor ID */
3133 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3137 * We can't leave this to comm_handle() because we must
3138 * fill in the cookie.
3141 struct isakmp_hdr r_hdr
= md
->hdr
;
3143 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
3144 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
3145 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
3146 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
3147 return STF_INTERNAL_ERROR
;
3150 /* start of SA out */
3152 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
3154 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
3156 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
3157 return STF_INTERNAL_ERROR
;
3160 /* SA body in and out */
3161 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
3162 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
3164 /* if enabled send Pluto Vendor ID */
3167 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3168 , &md
->rbody
, VID_STRONGSWAN
))
3170 return STF_INTERNAL_ERROR
;
3174 /* if enabled send Cisco Unity Vendor ID */
3175 if (SEND_CISCO_UNITY_VID
)
3177 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3178 , &md
->rbody
, VID_CISCO_UNITY
))
3180 return STF_INTERNAL_ERROR
;
3185 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3189 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3190 , &md
->rbody
, VID_OPENPGP
))
3192 return STF_INTERNAL_ERROR
;
3196 /* Announce our ability to do eXtended AUTHentication to the peer */
3199 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3200 , &md
->rbody
, VID_MISC_XAUTH
))
3202 return STF_INTERNAL_ERROR
;
3206 /* Announce our ability to do Dead Peer Detection to the peer */
3207 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3208 , &md
->rbody
, VID_MISC_DPD
))
3210 return STF_INTERNAL_ERROR
;
3213 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3215 /* reply if NAT-Traversal draft is supported */
3216 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3218 if (st
->nat_traversal
3219 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3220 , &md
->rbody
, md
->nat_traversal_vid
))
3222 return STF_INTERNAL_ERROR
;
3226 close_message(&md
->rbody
);
3228 /* save initiator SA for HASH */
3229 clonereplacechunk(st
->st_p1isa
, sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
), "sa in main_inI1_outR1()");
3234 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3235 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3237 * The following are not yet implemented:
3238 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3239 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3240 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3242 * We must verify that the proposal received matches one we sent.
3245 main_inR1_outI2(struct msg_digest
*md
)
3247 struct state
*const st
= md
->st
;
3249 u_int8_t np
= ISAKMP_NEXT_NONE
;
3251 /* verify echoed SA */
3253 u_int32_t ipsecdoisit
;
3254 pb_stream proposal_pbs
;
3255 struct isakmp_proposal proposal
;
3256 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3258 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3259 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3260 if (proposal
.isap_notrans
!= 1)
3262 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3263 , (unsigned)proposal
.isap_notrans
);
3264 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3266 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3267 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3270 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3272 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3273 plog("enabling possible NAT-traversal with method %s"