1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
26 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
27 #include <sys/queue.h>
28 #include <sys/time.h> /* for gettimeofday */
33 #include <asn1/asn1.h>
34 #include <crypto/hashers/hasher.h>
35 #include <crypto/prfs/prf.h>
36 #include <crypto/rngs/rng.h>
37 #include <credentials/keys/private_key.h>
38 #include <credentials/keys/public_key.h>
40 #include "constants.h"
49 #include "smartcard.h"
50 #include "connections.h"
53 #include "demux.h" /* needs packet.h */
54 #include "adns.h" /* needs <resolv.h> */
55 #include "dnskey.h" /* needs keys.h and adns.h */
62 #include "ipsec_doi.h" /* needs demux.h and state.h */
70 #include "kernel_alg.h"
71 #include "nat_traversal.h"
75 * are we sending Pluto's Vendor ID?
78 #define SEND_PLUTO_VID 1
80 #define SEND_PLUTO_VID 0
81 #endif /* !VENDORID */
84 * are we sending an XAUTH VID?
87 #define SEND_XAUTH_VID 1
88 #else /* !XAUTH_VID */
89 #define SEND_XAUTH_VID 0
90 #endif /* !XAUTH_VID */
93 * are we sending a Cisco Unity VID?
96 #define SEND_CISCO_UNITY_VID 1
97 #else /* !CISCO_QUIRKS */
98 #define SEND_CISCO_UNITY_VID 0
99 #endif /* !CISCO_QUIRKS */
101 /* MAGIC: perform f, a function that returns notification_t
102 * and return from the ENCLOSING stf_status returning function if it fails.
104 #define RETURN_STF_FAILURE(f) \
105 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
107 /* create output HDR as replica of input HDR */
109 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
111 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
113 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
115 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
116 /* some day, we may have to set r_hdr.isa_version */
118 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
119 impossible(); /* surely must have room and be well-formed */
122 /* Compute DH shared secret from our local secret and the peer's public value.
123 * We make the leap that the length should be that of the group
124 * (see quoted passage at start of ACCEPT_KE).
126 static void compute_dh_shared(struct state
*st
, const chunk_t g
)
129 st
->st_dh
->set_other_public_value(st
->st_dh
, g
);
130 st
->st_dh
->get_shared_secret(st
->st_dh
, &st
->st_shared
);
131 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
134 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
135 * the corresponding public value (g). This is emitted as a KE payload.
137 static bool build_and_ship_KE(struct state
*st
, chunk_t
*g
,
138 const struct dh_desc
*group
,
139 pb_stream
*outs
, u_int8_t np
)
141 if (st
->st_dh
== NULL
)
143 st
->st_dh
= lib
->crypto
->create_dh(lib
->crypto
, group
->algo_id
);
144 if (st
->st_dh
== NULL
)
146 plog("Diffie Hellman group %N is not available",
147 diffie_hellman_group_names
, group
->algo_id
);
151 st
->st_dh
->get_my_public_value(st
->st_dh
, g
);
153 DBG_dump_chunk("Public DH value sent:\n", *g
)
155 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
160 * Check and accept DH public value (Gi or Gr) from peer's message.
161 * According to RFC2409 "The Internet key exchange (IKE)" 5:
162 * The Diffie-Hellman public value passed in a KE payload, in either
163 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
164 * Diffie-Hellman group enforced, if necessary, by pre-pending the
167 static notification_t
accept_KE(chunk_t
*dest
, const char *val_name
,
168 const struct dh_desc
*gr
,
171 if (pbs_left(pbs
) != gr
->ke_size
)
173 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
174 , (unsigned) pbs_left(pbs
), gr
->ke_size
);
175 /* XXX Could send notification back */
176 return INVALID_KEY_INFORMATION
;
179 *dest
= chunk_create(pbs
->cur
, pbs_left(pbs
));
180 *dest
= chunk_clone(*dest
);
181 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
182 return NOTHING_WRONG
;
187 * Check and accept optional Quick Mode KE payload for PFS.
188 * Extends ACCEPT_PFS to check whether KE is allowed or required.
190 static notification_t
accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
,
191 const char *val_name
, const char *msg_name
)
193 struct state
*st
= md
->st
;
194 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
198 if (st
->st_pfs_group
!= NULL
)
200 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
201 return INVALID_KEY_INFORMATION
;
206 if (st
->st_pfs_group
== NULL
)
208 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
210 return INVALID_KEY_INFORMATION
;
212 if (ke_pd
->next
!= NULL
)
214 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
215 return INVALID_KEY_INFORMATION
; /* ??? */
217 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
219 return NOTHING_WRONG
;
222 static bool build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
,
228 *n
= chunk_create(malloc(DEFAULT_NONCE_SIZE
), DEFAULT_NONCE_SIZE
);
229 rng
= lib
->crypto
->create_rng(lib
->crypto
, RNG_WEAK
);
230 rng
->get_bytes(rng
, DEFAULT_NONCE_SIZE
, n
->ptr
);
232 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
235 static bool collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
237 struct connection
*d
= find_host_connection(&md
->iface
->addr
238 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
240 for (; d
!= NULL
; d
= d
->hp_next
)
242 /* must be a road warrior connection */
243 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
244 && d
->spd
.that
.ca
.ptr
!= NULL
)
247 bool new_entry
= TRUE
;
249 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
251 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
259 gn
= malloc_thing(generalName_t
);
260 gn
->kind
= GN_DIRECTORY_NAME
;
261 gn
->name
= d
->spd
.that
.ca
;
270 static bool build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
,
274 struct isakmp_cr cr_hd
;
276 cr_hd
.isacr_type
= type
;
278 /* build CR header */
279 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
284 /* build CR body containing the distinguished name of the CA */
285 if (!out_chunk(ca
, &cr_pbs
, "CA"))
288 close_output_pbs(&cr_pbs
);
292 /* Send a notification to the peer. We could decide
293 * whether to send the notification, based on the type and the
294 * destination, if we care to.
296 static void send_notification(struct state
*sndst
, u_int16_t type
,
297 struct state
*encst
, msgid_t msgid
,
298 u_char
*icookie
, u_char
*rcookie
,
299 u_char
*spi
, size_t spisize
, u_char protoid
)
302 pb_stream pbs
, r_hdr_pbs
;
303 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
304 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
306 passert((sndst
) && (sndst
->st_connection
));
308 plog("sending %snotification %s to %s:%u"
309 , encst ?
"encrypted " : ""
310 , enum_name(¬ification_names
, type
)
311 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
312 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
314 memset(buffer
, 0, sizeof(buffer
));
315 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
319 struct isakmp_hdr hdr
;
321 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
322 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
323 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
324 hdr
.isa_msgid
= msgid
;
325 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
327 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
329 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
330 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
334 /* HASH -- value to be filled later */
338 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
341 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
343 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
345 close_output_pbs(&hash_pbs
);
346 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
349 /* Notification Payload */
352 struct isakmp_notification isan
;
354 isan
.isan_doi
= ISAKMP_DOI_IPSEC
;
355 isan
.isan_np
= ISAKMP_NEXT_NONE
;
356 isan
.isan_type
= type
;
357 isan
.isan_spisize
= spisize
;
358 isan
.isan_protoid
= protoid
;
360 if (!out_struct(&isan
, &isakmp_notification_desc
, &r_hdr_pbs
, ¬_pbs
)
361 || !out_raw(spi
, spisize
, ¬_pbs
, "spi"))
363 close_output_pbs(¬_pbs
);
366 /* calculate hash value and patch into Hash Payload */
369 chunk_t msgid_chunk
= chunk_from_thing(msgid
);
370 chunk_t msg_chunk
= { r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
};
371 pseudo_random_function_t prf_alg
;
374 prf_alg
= oakley_to_prf(encst
->st_oakley
.hash
);
375 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
376 prf
->set_key(prf
, encst
->st_skeyid_a
);
377 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
378 prf
->get_bytes(prf
, msg_chunk
, r_hashval
);
381 DBG_log("HASH computed:");
382 DBG_dump("", r_hashval
, prf
->get_block_size(prf
));
387 /* Encrypt message (preserve st_iv and st_new_iv) */
390 u_char old_iv
[MAX_DIGEST_LEN
];
391 u_char new_iv
[MAX_DIGEST_LEN
];
393 u_int old_iv_len
= encst
->st_iv_len
;
394 u_int new_iv_len
= encst
->st_new_iv_len
;
396 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
399 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
400 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
402 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
404 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
405 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
407 init_phase2_iv(encst
, &msgid
);
408 if (!encrypt_message(&r_hdr_pbs
, encst
))
411 /* restore preserved st_iv and st_new_iv */
412 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
413 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
414 encst
->st_iv_len
= old_iv_len
;
415 encst
->st_new_iv_len
= new_iv_len
;
419 close_output_pbs(&r_hdr_pbs
);
422 /* Send packet (preserve st_tpacket) */
424 chunk_t saved_tpacket
= sndst
->st_tpacket
;
426 sndst
->st_tpacket
= chunk_create(pbs
.start
, pbs_offset(&pbs
));
427 send_packet(sndst
, "ISAKMP notify");
428 sndst
->st_tpacket
= saved_tpacket
;
432 void send_notification_from_state(struct state
*st
, enum state_kind state
,
439 if (state
== STATE_UNDEFINED
)
440 state
= st
->st_state
;
444 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
445 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
)))
447 loglog(RC_LOG_SERIOUS
,
448 "no Phase1 state for Quick mode notification");
451 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
452 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
454 else if (IS_ISAKMP_ENCRYPTED(state
) && st
->st_enc_key
.ptr
!= NULL
)
456 send_notification(st
, type
, st
, generate_msgid(st
),
457 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
461 /* no ISAKMP SA established - don't encrypt notification */
462 send_notification(st
, type
, NULL
, 0,
463 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
467 void send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
470 * Create a dummy state to be able to use send_packet in
474 * st_connection->that.host_addr
475 * st_connection->that.host_port
476 * st_connection->interface
479 struct connection cnx
;
483 memset(&st
, 0, sizeof(st
));
484 memset(&cnx
, 0, sizeof(cnx
));
485 st
.st_connection
= &cnx
;
486 cnx
.spd
.that
.host_addr
= md
->sender
;
487 cnx
.spd
.that
.host_port
= md
->sender_port
;
488 cnx
.interface
= md
->iface
;
490 send_notification(&st
, type
, NULL
, 0,
491 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
494 /* Send a Delete Notification to announce deletion of ISAKMP SA or
495 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
496 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
498 void send_delete(struct state
*st
)
505 ip_said said
[EM_MAXRELSPIS
];
508 *r_hashval
, /* where in reply to jam hash value */
509 *r_hash_start
; /* start of what is to be hashed */
510 bool isakmp_sa
= FALSE
;
512 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
514 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
517 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
521 if (st
->st_ah
.present
)
523 ns
->spi
= st
->st_ah
.our_spi
;
524 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
525 ns
->proto
= PROTO_IPSEC_AH
;
528 if (st
->st_esp
.present
)
530 ns
->spi
= st
->st_esp
.our_spi
;
531 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
532 ns
->proto
= PROTO_IPSEC_ESP
;
536 passert(ns
!= said
); /* there must be some SAs to delete */
538 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
545 return; /* nothing to do */
548 msgid
= generate_msgid(p1st
);
551 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
555 struct isakmp_hdr hdr
;
557 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
558 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
559 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
560 hdr
.isa_msgid
= msgid
;
561 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
562 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
563 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
564 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
568 /* HASH -- value to be filled later */
572 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
574 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
575 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
577 close_output_pbs(&hash_pbs
);
578 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
581 /* Delete Payloads */
585 struct isakmp_delete isad
;
586 u_char isakmp_spi
[2*COOKIE_SIZE
];
588 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
589 isad
.isad_np
= ISAKMP_NEXT_NONE
;
590 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
591 isad
.isad_protoid
= PROTO_ISAKMP
;
594 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
595 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
597 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
598 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
600 close_output_pbs(&del_pbs
);
608 struct isakmp_delete isad
;
611 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
612 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
613 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
614 isad
.isad_protoid
= ns
->proto
;
617 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
618 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
620 close_output_pbs(&del_pbs
);
624 /* calculate hash value and patch into Hash Payload */
626 chunk_t msgid_chunk
= chunk_from_thing(msgid
);
627 chunk_t msg_chunk
= { r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
};
628 pseudo_random_function_t prf_alg
;
631 prf_alg
= oakley_to_prf(p1st
->st_oakley
.hash
);
632 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
633 prf
->set_key(prf
, p1st
->st_skeyid_a
);
634 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
635 prf
->get_bytes(prf
, msg_chunk
, r_hashval
);
638 DBG_log("HASH(1) computed:");
639 DBG_dump("", r_hashval
, prf
->get_block_size(prf
));
645 /* Do a dance to avoid needing a new state object.
646 * We use the Phase 1 State. This is the one with right
648 * The tricky bits are:
649 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
650 * - we need to preserve (save/restore) st_tpacket.
653 u_char old_iv
[MAX_DIGEST_LEN
];
654 chunk_t saved_tpacket
= p1st
->st_tpacket
;
656 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
657 init_phase2_iv(p1st
, &msgid
);
659 if (!encrypt_message(&r_hdr_pbs
, p1st
))
662 p1st
->st_tpacket
= chunk_create(reply_pbs
.start
, pbs_offset(&reply_pbs
));
663 send_packet(p1st
, "delete notify");
664 p1st
->st_tpacket
= saved_tpacket
;
666 /* get back old IV for this state */
667 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
671 void accept_delete(struct state
*st
, struct msg_digest
*md
,
672 struct payload_digest
*p
)
674 struct isakmp_delete
*d
= &(p
->payload
.delete);
680 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
684 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
686 /* can't happen (if msg is encrypt), but just to be sure */
687 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
688 "ISAKMP SA not established");
692 if (d
->isad_nospi
== 0)
694 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
698 switch (d
->isad_protoid
)
701 sizespi
= 2 * COOKIE_SIZE
;
704 case PROTO_IPSEC_ESP
:
705 sizespi
= sizeof(ipsec_spi_t
);
708 /* nothing interesting to delete */
711 loglog(RC_LOG_SERIOUS
712 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
713 , enum_show(&protocol_names
, d
->isad_protoid
));
717 if (d
->isad_spisize
!= sizespi
)
719 loglog(RC_LOG_SERIOUS
720 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
721 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
725 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
727 loglog(RC_LOG_SERIOUS
728 , "ignoring Delete SA payload: invalid payload size");
732 for (i
= 0; i
< d
->isad_nospi
; i
++)
734 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
736 if (d
->isad_protoid
== PROTO_ISAKMP
)
741 struct state
*dst
= find_state(spi
/*iCookie*/
742 , spi
+COOKIE_SIZE
/*rCookie*/
743 , &st
->st_connection
->spd
.that
.host_addr
748 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
749 "ISAKMP SA not found (maybe expired)");
751 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
753 /* we've not authenticated the relevant identities */
754 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
755 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
759 struct connection
*oldc
;
761 oldc
= cur_connection
;
762 set_cur_connection(dst
->st_connection
);
764 if (nat_traversal_enabled
)
765 nat_traversal_change_port_lookup(md
, dst
);
767 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
768 "deleting ISAKMP State #%lu", dst
->st_serialno
);
770 set_cur_connection(oldc
);
779 struct state
*dst
= find_phase2_state_to_delete(st
781 , *(ipsec_spi_t
*)spi
/* network order */
786 loglog(RC_LOG_SERIOUS
787 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
788 , enum_show(&protocol_names
, d
->isad_protoid
)
789 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
790 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
794 struct connection
*rc
= dst
->st_connection
;
795 struct connection
*oldc
;
797 oldc
= cur_connection
;
798 set_cur_connection(rc
);
800 if (nat_traversal_enabled
)
801 nat_traversal_change_port_lookup(md
, dst
);
803 if (rc
->newest_ipsec_sa
== dst
->st_serialno
804 && (rc
->policy
& POLICY_UP
))
806 /* Last IPSec SA for a permanent connection that we
807 * have initiated. Replace it in a few seconds.
809 * Useful if the other peer is rebooting.
811 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
812 if (dst
->st_event
!= NULL
813 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
814 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
816 /* Patch from Angus Lees to ignore retransmited
819 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
820 "already replacing IPSEC State #%lu in %d seconds"
821 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
825 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
826 "replace IPSEC State #%lu in %d seconds"
827 , dst
->st_serialno
, DELETE_SA_DELAY
);
828 dst
->st_margin
= DELETE_SA_DELAY
;
830 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
835 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
836 "deleting IPSEC State #%lu"
837 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
842 /* reset connection */
843 set_cur_connection(oldc
);
849 /* The whole message must be a multiple of 4 octets.
850 * I'm not sure where this is spelled out, but look at
851 * rfc2408 3.6 Transform Payload.
852 * Note: it talks about 4 BYTE boundaries!
854 void close_message(pb_stream
*pbs
)
856 size_t padding
= pad_up(pbs_offset(pbs
), 4);
859 (void) out_zero(padding
, pbs
, "message padding");
860 close_output_pbs(pbs
);
863 /* Initiate an Oakley Main Mode exchange.
865 * Note: this is not called from demux.c
868 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
869 , lset_t policy
, unsigned long try)
871 struct state
*st
= new_state();
872 pb_stream reply
; /* not actually a reply, but you know what I mean */
875 int vids_to_send
= 0;
877 /* set up new state */
878 st
->st_connection
= c
;
879 set_cur_state(st
); /* we must reset before exit */
880 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
881 st
->st_whack_sock
= whack_sock
;
883 st
->st_state
= STATE_MAIN_I1
;
885 /* determine how many Vendor ID payloads we will be sending */
888 if (SEND_CISCO_UNITY_VID
)
890 if (c
->spd
.this.cert
.type
== CERT_PGP
)
894 /* always send DPD Vendor ID */
896 if (nat_traversal_enabled
)
899 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
901 insert_state(st
); /* needs cookies, connection, and msgid (0) */
903 if (HAS_IPSEC_POLICY(policy
))
904 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
905 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
907 if (predecessor
== NULL
)
908 plog("initiating Main Mode");
910 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
913 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
917 struct isakmp_hdr hdr
;
919 zero(&hdr
); /* default to 0 */
920 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
921 hdr
.isa_np
= ISAKMP_NEXT_SA
;
922 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
923 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
924 /* R-cookie, flags and MessageID are left zero */
926 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
929 return STF_INTERNAL_ERROR
;
935 u_char
*sa_start
= rbody
.cur
;
937 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
938 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
941 return STF_INTERNAL_ERROR
;
944 /* save initiator SA for later HASH */
945 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
946 st
->st_p1isa
= chunk_create(sa_start
, rbody
.cur
- sa_start
);
947 st
->st_p1isa
= chunk_clone(st
->st_p1isa
);
950 /* if enabled send Pluto Vendor ID */
953 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
954 , &rbody
, VID_STRONGSWAN
))
957 return STF_INTERNAL_ERROR
;
961 /* if enabled send Cisco Unity Vendor ID */
962 if (SEND_CISCO_UNITY_VID
)
964 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
965 , &rbody
, VID_CISCO_UNITY
))
968 return STF_INTERNAL_ERROR
;
971 /* if we have an OpenPGP certificate we assume an
972 * OpenPGP peer and have to send the Vendor ID
974 if (c
->spd
.this.cert
.type
== CERT_PGP
)
976 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
977 , &rbody
, VID_OPENPGP
))
980 return STF_INTERNAL_ERROR
;
984 /* Announce our ability to do eXtended AUTHentication to the peer */
987 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
988 , &rbody
, VID_MISC_XAUTH
))
991 return STF_INTERNAL_ERROR
;
995 /* Announce our ability to do Dead Peer Detection to the peer */
997 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
998 , &rbody
, VID_MISC_DPD
))
1001 return STF_INTERNAL_ERROR
;
1005 if (nat_traversal_enabled
)
1007 /* Add supported NAT-Traversal VID */
1008 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1012 return STF_INTERNAL_ERROR
;
1016 close_message(&rbody
);
1017 close_output_pbs(&reply
);
1018 st
->st_tpacket
= chunk_create(reply
.start
, pbs_offset(&reply
));
1019 st
->st_tpacket
= chunk_clone(st
->st_tpacket
);
1023 send_packet(st
, "main_outI1");
1025 /* Set up a retransmission event, half a minute henceforth */
1027 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1029 if (predecessor
!= NULL
)
1031 update_pending(predecessor
, st
);
1032 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1033 , "%s: initiate, replacing #%lu"
1034 , enum_name(&state_names
, st
->st_state
)
1035 , predecessor
->st_serialno
);
1039 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1040 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1046 void ipsecdoi_initiate(int whack_sock
, struct connection
*c
, lset_t policy
,
1047 unsigned long try, so_serial_t replacing
)
1049 /* If there's already an ISAKMP SA established, use that and
1050 * go directly to Quick Mode. We are even willing to use one
1051 * that is still being negotiated, but only if we are the Initiator
1052 * (thus we can be sure that the IDs are not going to change;
1053 * other issues around intent might matter).
1054 * Note: there is no way to initiate with a Road Warrior.
1056 struct state
*st
= find_phase1_state(c
1057 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1061 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1063 else if (HAS_IPSEC_POLICY(policy
))
1065 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1067 /* leave our Phase 2 negotiation pending */
1068 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1072 /* ??? we assume that peer_nexthop_sin isn't important:
1073 * we already have it from when we negotiated the ISAKMP SA!
1074 * It isn't clear what to do with the error return.
1076 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1081 close_any(whack_sock
);
1085 /* Replace SA with a fresh one that is similar
1087 * Shares some logic with ipsecdoi_initiate, but not the same!
1088 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1089 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1090 * ISAKMP SA if needed.
1091 * - duplicate whack fd, if live.
1092 * Does not delete the old state -- someone else will do that.
1094 void ipsecdoi_replace(struct state
*st
, unsigned long try)
1096 int whack_sock
= dup_any(st
->st_whack_sock
);
1097 lset_t policy
= st
->st_policy
;
1099 if (IS_PHASE1(st
->st_state
))
1101 passert(!HAS_IPSEC_POLICY(policy
));
1102 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1106 /* Add features of actual old state to policy. This ensures
1107 * that rekeying doesn't downgrade security. I admit that
1108 * this doesn't capture everything.
1110 if (st
->st_pfs_group
!= NULL
)
1111 policy
|= POLICY_PFS
;
1112 if (st
->st_ah
.present
)
1114 policy
|= POLICY_AUTHENTICATE
;
1115 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1116 policy
|= POLICY_TUNNEL
;
1118 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1120 policy
|= POLICY_ENCRYPT
;
1121 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1122 policy
|= POLICY_TUNNEL
;
1124 if (st
->st_ipcomp
.present
)
1126 policy
|= POLICY_COMPRESS
;
1127 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1128 policy
|= POLICY_TUNNEL
;
1130 passert(HAS_IPSEC_POLICY(policy
));
1131 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1136 /* SKEYID for preshared keys.
1137 * See draft-ietf-ipsec-ike-01.txt 4.1
1139 static bool skeyid_preshared(struct state
*st
)
1141 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1145 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1150 pseudo_random_function_t prf_alg
;
1153 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1154 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1157 loglog(RC_LOG_SERIOUS
, "%N not available to compute skeyid",
1158 pseudo_random_function_names
, prf_alg
);
1161 free(st
->st_skeyid
.ptr
);
1162 prf
->set_key(prf
, *pss
);
1163 prf
->allocate_bytes(prf
, st
->st_ni
, NULL
);
1164 prf
->allocate_bytes(prf
, st
->st_nr
, &st
->st_skeyid
);
1171 skeyid_digisig(struct state
*st
)
1174 pseudo_random_function_t prf_alg
;
1177 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1178 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1181 loglog(RC_LOG_SERIOUS
, "%N not available to compute skeyid",
1182 pseudo_random_function_names
, prf_alg
);
1185 free(st
->st_skeyid
.ptr
);
1186 nir
= chunk_cat("cc", st
->st_ni
, st
->st_nr
);
1187 prf
->set_key(prf
, nir
);
1188 prf
->allocate_bytes(prf
, st
->st_shared
, &st
->st_skeyid
);
1194 /* Generate the SKEYID_* and new IV
1195 * See draft-ietf-ipsec-ike-01.txt 4.1
1197 static bool generate_skeyids_iv(struct state
*st
)
1199 /* Generate the SKEYID */
1200 switch (st
->st_oakley
.auth
)
1202 case OAKLEY_PRESHARED_KEY
:
1203 case XAUTHInitPreShared
:
1204 case XAUTHRespPreShared
:
1205 if (!skeyid_preshared(st
))
1211 case OAKLEY_RSA_SIG
:
1214 if (!skeyid_digisig(st
))
1220 case OAKLEY_DSS_SIG
:
1223 case OAKLEY_RSA_ENC
:
1224 case OAKLEY_RSA_ENC_REV
:
1225 case OAKLEY_ELGAMAL_ENC
:
1226 case OAKLEY_ELGAMAL_ENC_REV
:
1230 bad_case(st
->st_oakley
.auth
);
1233 /* generate SKEYID_* from SKEYID */
1235 char buf_skeyid_d
[] = { 0x00 };
1236 char buf_skeyid_a
[] = { 0x01 };
1237 char buf_skeyid_e
[] = { 0x02 };
1238 chunk_t seed_skeyid_d
= chunk_from_buf(buf_skeyid_d
);
1239 chunk_t seed_skeyid_a
= chunk_from_buf(buf_skeyid_a
);
1240 chunk_t seed_skeyid_e
= chunk_from_buf(buf_skeyid_e
);
1241 chunk_t icookie
= { st
->st_icookie
, COOKIE_SIZE
};
1242 chunk_t rcookie
= { st
->st_rcookie
, COOKIE_SIZE
};
1243 pseudo_random_function_t prf_alg
;
1246 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1247 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1248 prf
->set_key(prf
, st
->st_skeyid
);
1251 free(st
->st_skeyid_d
.ptr
);
1252 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1253 prf
->allocate_bytes(prf
, icookie
, NULL
);
1254 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1255 prf
->allocate_bytes(prf
, seed_skeyid_d
, &st
->st_skeyid_d
);
1258 free(st
->st_skeyid_a
.ptr
);
1259 prf
->allocate_bytes(prf
, st
->st_skeyid_d
, NULL
);
1260 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1261 prf
->allocate_bytes(prf
, icookie
, NULL
);
1262 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1263 prf
->allocate_bytes(prf
, seed_skeyid_a
, &st
->st_skeyid_a
);
1266 free(st
->st_skeyid_e
.ptr
);
1267 prf
->allocate_bytes(prf
, st
->st_skeyid_a
, NULL
);
1268 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1269 prf
->allocate_bytes(prf
, icookie
, NULL
);
1270 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1271 prf
->allocate_bytes(prf
, seed_skeyid_e
, &st
->st_skeyid_e
);
1278 hash_algorithm_t hash_alg
;
1281 hash_alg
= oakley_to_hash_algorithm(st
->st_oakley
.hash
);
1282 hasher
= lib
->crypto
->create_hasher(lib
->crypto
, hash_alg
);
1283 st
->st_new_iv_len
= hasher
->get_hash_size(hasher
);
1284 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1287 DBG_dump_chunk("DH_i:", st
->st_gi
);
1288 DBG_dump_chunk("DH_r:", st
->st_gr
);
1291 hasher
->get_hash(hasher
, st
->st_gi
, NULL
);
1292 hasher
->get_hash(hasher
, st
->st_gr
, st
->st_new_iv
);
1293 hasher
->destroy(hasher
);
1296 /* Oakley Keying Material
1297 * Derived from Skeyid_e: if it is not big enough, generate more
1299 * See RFC 2409 "IKE" Appendix B
1302 size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1304 /* free any existing key */
1305 free(st
->st_enc_key
.ptr
);
1307 if (keysize
> st
->st_skeyid_e
.len
)
1309 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1310 char seed_buf
[] = { 0x00 };
1311 chunk_t seed
= chunk_from_buf(seed_buf
);
1312 size_t prf_block_size
, i
;
1313 pseudo_random_function_t prf_alg
;
1316 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1317 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1318 prf
->set_key(prf
, st
->st_skeyid_e
);
1319 prf_block_size
= prf
->get_block_size(prf
);
1323 prf
->get_bytes(prf
, seed
, &keytemp
[i
]);
1324 i
+= prf_block_size
;
1329 seed
= chunk_create(&keytemp
[i
-prf_block_size
], prf_block_size
);
1332 st
->st_enc_key
= chunk_create(keytemp
, keysize
);
1336 st
->st_enc_key
= chunk_create(st
->st_skeyid_e
.ptr
, keysize
);
1338 st
->st_enc_key
= chunk_clone(st
->st_enc_key
);
1342 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1343 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1344 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1345 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1346 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1347 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1351 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1352 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1353 * New Group Mode, or ISAKMP Informational Exchanges).
1354 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1355 * If hashus argument is TRUE, we're generating a hash for our end.
1356 * See RFC2409 IKE 5.
1358 static size_t main_mode_hash(struct state
*st
, u_char
*hash_val
, bool hashi
,
1359 const pb_stream
*idpl
)
1361 chunk_t icookie
= { st
->st_icookie
, COOKIE_SIZE
};
1362 chunk_t rcookie
= { st
->st_rcookie
, COOKIE_SIZE
};
1363 chunk_t sa_body
= { st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
),
1364 st
->st_p1isa
.len
- sizeof(struct isakmp_generic
) };
1365 chunk_t id_body
= { idpl
->start
+ sizeof(struct isakmp_generic
),
1366 pbs_offset(idpl
) - sizeof(struct isakmp_generic
) };
1367 pseudo_random_function_t prf_alg
;
1369 size_t prf_block_size
;
1371 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1372 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1373 prf
->set_key(prf
, st
->st_skeyid
);
1377 prf
->get_bytes(prf
, st
->st_gi
, NULL
);
1378 prf
->get_bytes(prf
, st
->st_gr
, NULL
);
1379 prf
->get_bytes(prf
, icookie
, NULL
);
1380 prf
->get_bytes(prf
, rcookie
, NULL
);
1384 prf
->get_bytes(prf
, st
->st_gr
, NULL
);
1385 prf
->get_bytes(prf
, st
->st_gi
, NULL
);
1386 prf
->get_bytes(prf
, rcookie
, NULL
);
1387 prf
->get_bytes(prf
, icookie
, NULL
);
1391 DBG_log("hashing %u bytes of SA", sa_body
.len
)
1393 prf
->get_bytes(prf
, sa_body
, NULL
);
1395 /* Hash identification payload, without generic payload header.
1396 * We used to reconstruct ID Payload for this purpose, but now
1397 * we use the bytes as they appear on the wire to avoid
1398 * "spelling problems".
1400 prf
->get_bytes(prf
, id_body
, hash_val
);
1401 prf_block_size
= prf
->get_block_size(prf
);
1404 return prf_block_size
;
1407 /* Create a public key signature of a hash.
1408 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1409 * Use PKCS#1 version 1.5 encryption of hash (called
1410 * RSAES-PKCS1-V1_5) in PKCS#2.
1412 static size_t sign_hash(struct connection
*c
, u_char sig_val
[RSA_MAX_OCTETS
],
1413 u_char
*hash_val
, size_t hash_len
)
1416 smartcard_t
*sc
= c
->spd
.this.sc
;
1418 if (sc
== NULL
) /* no smartcard */
1421 private_key_t
*private = get_private_key(c
);
1423 if (private == NULL
)
1425 return 0; /* failure: no key to use */
1427 sz
= private->get_keysize(private);
1428 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1429 hash
= chunk_create(hash_val
, hash_len
);
1430 sig
= chunk_create(sig_val
, sz
);
1431 if (!private->sign(private, SIGN_RSA_EMSA_PKCS1_NULL
, hash
, &sig
))
1435 memcpy(sig_val
, sig
.ptr
, sz
);
1438 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1440 lock_certs_and_keys("sign_hash");
1441 if (!scx_establish_context(sc
) || !scx_login(sc
))
1443 scx_release_context(sc
);
1444 unlock_certs_and_keys("sign_hash");
1448 sz
= scx_get_keylength(sc
);
1451 plog("failed to get keylength from smartcard");
1452 scx_release_context(sc
);
1453 unlock_certs_and_keys("sign_hash");
1457 DBG(DBG_CONTROL
| DBG_CRYPT
,
1458 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1459 , (int)sc
->slot
, sc
->id
)
1461 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1462 if (!pkcs11_keep_state
)
1463 scx_release_context(sc
);
1464 unlock_certs_and_keys("sign_hash");
1469 /* Check signature against all RSA public keys we can find.
1470 * If we need keys from DNS KEY records, and they haven't been fetched,
1471 * return STF_SUSPEND to ask for asynch DNS lookup.
1473 * Note: parameter keys_from_dns contains results of DNS lookup for key
1474 * or is NULL indicating lookup not yet tried.
1476 * take_a_crack is a helper function. Mostly forensic.
1477 * If only we had coroutines.
1483 int tried_cnt
; /* number of keys tried */
1486 static bool take_a_crack(struct tac_state
*s
, pubkey_t
*kr
)
1488 public_key_t
*pub_key
= kr
->public_key
;
1489 identification_t
*keyid
= pub_key
->get_id(pub_key
, ID_PUBKEY_SHA1
);
1493 if (pub_key
->verify(pub_key
, SIGN_RSA_EMSA_PKCS1_NULL
, s
->hash
, s
->sig
))
1495 DBG(DBG_CRYPT
| DBG_CONTROL
,
1496 DBG_log("signature check passed with keyid %Y", keyid
)
1498 unreference_key(&s
->st
->st_peer_pubkey
);
1499 s
->st
->st_peer_pubkey
= reference_key(kr
);
1505 DBG_log("signature check failed with keyid %Y", keyid
)
1511 static stf_status
RSA_check_signature(const struct id
* peer
, struct state
*st
,
1512 u_char hash_val
[MAX_DIGEST_LEN
],
1513 size_t hash_len
, const pb_stream
*sig_pbs
,
1515 const pubkey_list_t
*keys_from_dns
,
1516 #endif /* USE_KEYRR */
1517 const struct gw_info
*gateways_from_dns
)
1519 const struct connection
*c
= st
->st_connection
;
1523 s
.hash
= chunk_create(hash_val
, hash_len
);
1524 s
.sig
= chunk_create(sig_pbs
->cur
, pbs_left(sig_pbs
));
1527 /* try all gateway records hung off c */
1528 if (c
->policy
& POLICY_OPPO
)
1532 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1534 /* only consider entries that have a key and are for our peer */
1535 if (gw
->gw_key_present
&& same_id(&gw
->gw_id
, &c
->spd
.that
.id
)&&
1536 take_a_crack(&s
, gw
->key
))
1543 /* try all appropriate Public keys */
1545 pubkey_list_t
*p
, **pp
;
1549 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1551 pubkey_t
*key
= p
->key
;
1552 key_type_t type
= key
->public_key
->get_type(key
->public_key
);
1554 if (type
== KEY_RSA
&& same_id(peer
, &key
->id
))
1556 time_t now
= time(NULL
);
1558 /* check if found public key has expired */
1559 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1561 loglog(RC_LOG_SERIOUS
,
1562 "cached RSA public key has expired and has been deleted");
1563 *pp
= free_public_keyentry(p
);
1564 continue; /* continue with next public key */
1567 if (take_a_crack(&s
, key
))
1576 /* if no key was found and that side of connection is
1577 * key_from_DNS_on_demand then go search DNS for keys for peer.
1579 if (s
.tried_cnt
== 0 && c
->spd
.that
.key_from_DNS_on_demand
)
1581 if (gateways_from_dns
!= NULL
)
1584 const struct gw_info
*gwp
;
1586 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1588 if (gwp
->gw_key_present
&& take_a_crack(&s
, gwp
->key
))
1595 else if (keys_from_dns
!= NULL
)
1598 const pubkey_list_t
*kr
;
1600 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1602 if (kr
->key
->alg
== PUBKEY_ALG_RSA
&& take_a_crack(&s
, kr
->key
))
1608 #endif /* USE_KEYRR */
1611 /* nothing yet: ask for asynch DNS lookup */
1616 /* no acceptable key was found: diagnose */
1618 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1620 idtoa(peer
, id_buf
, sizeof(id_buf
));
1622 if (s
.tried_cnt
== 0)
1624 loglog(RC_LOG_SERIOUS
, "no public key known for '%s'", id_buf
);
1626 else if (s
.tried_cnt
== 1)
1628 loglog(RC_LOG_SERIOUS
, "signature check for '%s' failed: "
1629 " wrong key?; tried %d", id_buf
, s
.tried_cnt
);
1631 DBG_log("public key for '%s' failed: "
1632 "decrypted SIG payload into a malformed ECB", id_buf
)
1637 loglog(RC_LOG_SERIOUS
, "signature check for '%s' failed: "
1638 "tried %d keys but none worked.", id_buf
, s
.tried_cnt
);
1640 DBG_log("all %d public keys for '%s' failed: "
1641 "best decrypted SIG payload into a malformed ECB",
1642 s
.tried_cnt
, id_buf
)
1645 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1649 static notification_t
accept_nonce(struct msg_digest
*md
, chunk_t
*dest
,
1652 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1653 size_t len
= pbs_left(nonce_pbs
);
1655 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1657 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1658 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1659 return PAYLOAD_MALFORMED
; /* ??? */
1662 *dest
= chunk_create(nonce_pbs
->cur
, len
);
1663 *dest
= chunk_clone(*dest
);
1664 return NOTHING_WRONG
;
1667 /* encrypt message, sans fixed part of header
1668 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1669 * The theory is that there will be no "backing out", so we commit to IV.
1670 * We also close the pbs.
1673 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1675 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1676 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1679 size_t crypter_block_size
;
1680 encryption_algorithm_t enc_alg
;
1683 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1684 enc_alg
= oakley_to_encryption_algorithm(st
->st_oakley
.encrypt
);
1685 crypter
= lib
->crypto
->create_crypter(lib
->crypto
, enc_alg
, st
->st_enc_key
.len
);
1686 crypter_block_size
= crypter
->get_block_size(crypter
);
1688 /* Pad up to multiple of encryption blocksize.
1689 * See the description associated with the definition of
1690 * struct isakmp_hdr in packet.h.
1693 size_t padding
= pad_up(enc_len
, crypter_block_size
);
1697 if (!out_zero(padding
, pbs
, "encryption padding"))
1703 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1704 data
= chunk_create(enc_start
, enc_len
);
1706 /* form iv by truncation */
1707 st
->st_new_iv_len
= crypter_block_size
;
1708 iv
= chunk_create(st
->st_new_iv
, st
->st_new_iv_len
);
1710 crypter
->set_key(crypter
, st
->st_enc_key
);
1711 crypter
->encrypt(crypter
, data
, iv
, NULL
);
1712 crypter
->destroy(crypter
);
1714 new_iv
= data
.ptr
+ data
.len
- crypter_block_size
;
1715 memcpy(st
->st_new_iv
, new_iv
, crypter_block_size
);
1717 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1722 /* Compute HASH(1), HASH(2) of Quick Mode.
1723 * HASH(1) is part of Quick I1 message.
1724 * HASH(2) is part of Quick R1 message.
1725 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1726 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1728 static size_t quick_mode_hash12(u_char
*dest
, u_char
*start
, u_char
*roof
,
1729 const struct state
*st
, const msgid_t
*msgid
,
1732 chunk_t msgid_chunk
= chunk_from_thing(*msgid
);
1733 chunk_t msg_chunk
= { start
, roof
- start
};
1734 pseudo_random_function_t prf_alg
;
1736 size_t prf_block_size
;
1738 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1739 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1740 prf
->set_key(prf
, st
->st_skeyid_a
);
1741 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
1744 prf
->get_bytes(prf
, st
->st_ni
, NULL
); /* include Ni_b in the hash */
1746 prf
->get_bytes(prf
, msg_chunk
, dest
);
1747 prf_block_size
= prf
->get_block_size(prf
);
1751 DBG_log("HASH(%d) computed:", hash2
+ 1);
1752 DBG_dump("", dest
, prf_block_size
)
1754 return prf_block_size
;
1757 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1758 * Used by: quick_inR1_outI2, quick_inI2
1759 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1760 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1761 * Message ID and Nonces. This is a mistake.
1763 static size_t quick_mode_hash3(u_char
*dest
, struct state
*st
)
1765 char seed_buf
[] = { 0x00 };
1766 chunk_t seed_chunk
= chunk_from_buf(seed_buf
);
1767 chunk_t msgid_chunk
= chunk_from_thing(st
->st_msgid
);
1768 pseudo_random_function_t prf_alg
;
1770 size_t prf_block_size
;
1772 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1773 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1774 prf
->set_key(prf
, st
->st_skeyid_a
);
1775 prf
->get_bytes(prf
, seed_chunk
, NULL
);
1776 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
1777 prf
->get_bytes(prf
, st
->st_ni
, NULL
);
1778 prf
->get_bytes(prf
, st
->st_nr
, dest
);
1779 prf_block_size
= prf
->get_block_size(prf
);
1782 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, prf_block_size
);
1783 return prf_block_size
;
1786 /* Compute Phase 2 IV.
1787 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1789 void init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1791 chunk_t iv_chunk
= { st
->st_ph1_iv
, st
->st_ph1_iv_len
};
1792 chunk_t msgid_chunk
= chunk_from_thing(*msgid
);
1793 hash_algorithm_t hash_alg
;
1796 hash_alg
= oakley_to_hash_algorithm(st
->st_oakley
.hash
);
1797 hasher
= lib
->crypto
->create_hasher(lib
->crypto
, hash_alg
);
1799 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:",
1800 st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1802 st
->st_new_iv_len
= hasher
->get_hash_size(hasher
);
1803 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1805 hasher
->get_hash(hasher
, iv_chunk
, NULL
);
1806 hasher
->get_hash(hasher
, msgid_chunk
, st
->st_new_iv
);
1807 hasher
->destroy(hasher
);
1809 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:",
1810 st
->st_new_iv
, st
->st_new_iv_len
);
1813 /* Initiate quick mode.
1814 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1815 * (see RFC 2409 "IKE" 5.5)
1816 * Note: this is not called from demux.c
1819 static bool emit_subnet_id(ip_subnet
*net
, u_int8_t np
, u_int8_t protoid
,
1820 u_int16_t port
, pb_stream
*outs
)
1822 struct isakmp_ipsec_id id
;
1825 const unsigned char *tbp
;
1829 id
.isaiid_idtype
= subnetishost(net
)
1830 ?
aftoinfo(subnettypeof(net
))->id_addr
1831 : aftoinfo(subnettypeof(net
))->id_subnet
;
1832 id
.isaiid_protoid
= protoid
;
1833 id
.isaiid_port
= port
;
1835 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
1838 networkof(net
, &ta
);
1839 tal
= addrbytesptr(&ta
, &tbp
);
1840 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
1843 if (!subnetishost(net
))
1846 tal
= addrbytesptr(&ta
, &tbp
);
1847 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
1851 close_output_pbs(&id_pbs
);
1855 stf_status
quick_outI1(int whack_sock
, struct state
*isakmp_sa
,
1856 struct connection
*c
, lset_t policy
, unsigned long try,
1857 so_serial_t replacing
)
1859 struct state
*st
= duplicate_state(isakmp_sa
);
1860 pb_stream reply
; /* not really a reply */
1862 u_char
/* set by START_HASH_PAYLOAD: */
1863 *r_hashval
, /* where in reply to jam hash value */
1864 *r_hash_start
; /* start of what is to be hashed */
1865 bool has_client
= c
->spd
.this.has_client
|| c
->spd
.that
.has_client
||
1866 c
->spd
.this.protocol
|| c
->spd
.that
.protocol
||
1867 c
->spd
.this.port
|| c
->spd
.that
.port
;
1869 bool send_natoa
= FALSE
;
1870 u_int8_t np
= ISAKMP_NEXT_NONE
;
1872 st
->st_whack_sock
= whack_sock
;
1873 st
->st_connection
= c
;
1874 set_cur_state(st
); /* we must reset before exit */
1875 st
->st_policy
= policy
;
1878 st
->st_myuserprotoid
= c
->spd
.this.protocol
;
1879 st
->st_peeruserprotoid
= c
->spd
.that
.protocol
;
1880 st
->st_myuserport
= c
->spd
.this.port
;
1881 st
->st_peeruserport
= c
->spd
.that
.port
;
1883 st
->st_msgid
= generate_msgid(isakmp_sa
);
1884 st
->st_state
= STATE_QUICK_I1
;
1886 insert_state(st
); /* needs cookies, connection, and msgid */
1888 if (replacing
== SOS_NOBODY
)
1889 plog("initiating Quick Mode %s {using isakmp#%lu}"
1890 , prettypolicy(policy
)
1891 , isakmp_sa
->st_serialno
);
1893 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
1894 , prettypolicy(policy
)
1896 , isakmp_sa
->st_serialno
);
1898 if (isakmp_sa
->nat_traversal
& NAT_T_DETECTED
)
1900 /* Duplicate nat_traversal status in new state */
1901 st
->nat_traversal
= isakmp_sa
->nat_traversal
;
1903 if (isakmp_sa
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
))
1906 nat_traversal_change_port_lookup(NULL
, st
);
1909 st
->nat_traversal
= 0;
1911 /* are we going to send a NAT-OA payload? */
1912 if ((st
->nat_traversal
& NAT_T_WITH_NATOA
)
1913 && !(st
->st_policy
& POLICY_TUNNEL
)
1914 && (st
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
)))
1917 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
1918 ISAKMP_NEXT_NATOA_RFC
: ISAKMP_NEXT_NATOA_DRAFTS
;
1922 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
1926 struct isakmp_hdr hdr
;
1928 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
1929 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
1930 hdr
.isa_xchg
= ISAKMP_XCHG_QUICK
;
1931 hdr
.isa_msgid
= st
->st_msgid
;
1932 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
1933 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
1934 memcpy(hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
1935 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
1938 return STF_INTERNAL_ERROR
;
1942 /* HASH(1) -- create and note space to be filled later */
1943 START_HASH_PAYLOAD(rbody
, ISAKMP_NEXT_SA
);
1948 * See if pfs_group has been specified for this conn,
1949 * if not, fallback to old use-same-as-P1 behaviour
1952 if (st
->st_connection
)
1953 st
->st_pfs_group
= ike_alg_pfsgroup(st
->st_connection
, policy
);
1954 if (!st
->st_pfs_group
)
1956 /* If PFS specified, use the same group as during Phase 1:
1957 * since no negotiation is possible, we pick one that is
1958 * very likely supported.
1960 st
->st_pfs_group
= policy
& POLICY_PFS? isakmp_sa
->st_oakley
.group
: NULL
;
1962 /* Emit SA payload based on a subset of the policy bits.
1963 * POLICY_COMPRESS is considered iff we can do IPcomp.
1966 lset_t pm
= POLICY_ENCRYPT
| POLICY_AUTHENTICATE
;
1969 pm
|= POLICY_COMPRESS
;
1972 , &ipsec_sadb
[(st
->st_policy
& pm
) >> POLICY_IPSEC_SHIFT
]
1973 , st
, FALSE
, ISAKMP_NEXT_NONCE
))
1976 return STF_INTERNAL_ERROR
;
1981 if (!build_and_ship_nonce(&st
->st_ni
, &rbody
1982 , policy
& POLICY_PFS? ISAKMP_NEXT_KE
: has_client? ISAKMP_NEXT_ID
: np
1986 return STF_INTERNAL_ERROR
;
1989 /* [ KE ] out (for PFS) */
1991 if (st
->st_pfs_group
!= NULL
)
1993 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_pfs_group
1994 , &rbody
, has_client? ISAKMP_NEXT_ID
: np
))
1997 return STF_INTERNAL_ERROR
;
2001 /* [ IDci, IDcr ] out */
2004 /* IDci (we are initiator), then IDcr (peer is responder) */
2005 if (!emit_subnet_id(&c
->spd
.this.client
2006 , ISAKMP_NEXT_ID
, st
->st_myuserprotoid
, st
->st_myuserport
, &rbody
)
2007 || !emit_subnet_id(&c
->spd
.that
.client
2008 , np
, st
->st_peeruserprotoid
, st
->st_peeruserport
, &rbody
))
2011 return STF_INTERNAL_ERROR
;
2015 /* Send NAT-OA if our address is NATed */
2018 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE
, &rbody
, st
))
2021 return STF_INTERNAL_ERROR
;
2025 /* finish computing HASH(1), inserting it in output */
2026 (void) quick_mode_hash12(r_hashval
, r_hash_start
, rbody
.cur
2027 , st
, &st
->st_msgid
, FALSE
);
2029 /* encrypt message, except for fixed part of header */
2031 init_phase2_iv(isakmp_sa
, &st
->st_msgid
);
2032 st
->st_new_iv_len
= isakmp_sa
->st_new_iv_len
;
2033 memcpy(st
->st_new_iv
, isakmp_sa
->st_new_iv
, st
->st_new_iv_len
);
2035 if (!encrypt_message(&rbody
, st
))
2038 return STF_INTERNAL_ERROR
;
2041 /* save packet, now that we know its size */
2042 st
->st_tpacket
= chunk_create(reply
.start
, pbs_offset(&reply
));
2043 st
->st_tpacket
= chunk_clone(st
->st_tpacket
);
2045 /* send the packet */
2047 send_packet(st
, "quick_outI1");
2050 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
2052 if (replacing
== SOS_NOBODY
)
2053 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2055 , enum_name(&state_names
, st
->st_state
));
2057 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2058 , "%s: initiate to replace #%lu"
2059 , enum_name(&state_names
, st
->st_state
)
2067 * Decode the CERT payload of Phase 1.
2069 static void decode_cert(struct msg_digest
*md
)
2071 struct payload_digest
*p
;
2073 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2075 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2078 blob
.ptr
= p
->pbs
.cur
;
2079 blob
.len
= pbs_left(&p
->pbs
);
2080 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2082 x509cert_t cert
= empty_x509cert
;
2083 if (parse_x509cert(blob
, 0, &cert
))
2085 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2088 DBG_log("Public key validated")
2090 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2094 plog("X.509 certificate rejected");
2096 DESTROY_IF(cert
.public_key
);
2097 free_generalNames(cert
.subjectAltName
, FALSE
);
2098 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2101 plog("Syntax error in X.509 certificate");
2103 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2105 x509cert_t
*cert
= NULL
;
2107 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2108 store_x509certs(&cert
, strict_crl_policy
);
2110 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2114 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2115 enum_show(&cert_type_names
, cert
->isacert_type
));
2116 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2122 * Decode the CR payload of Phase 1.
2124 static void decode_cr(struct msg_digest
*md
, struct connection
*c
)
2126 struct payload_digest
*p
;
2128 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2130 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2133 ca_name
.len
= pbs_left(&p
->pbs
);
2134 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2136 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2138 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2142 if (ca_name
.len
> 0)
2146 if (!is_asn1(ca_name
))
2149 gn
= malloc_thing(generalName_t
);
2150 ca_name
= chunk_clone(ca_name
);
2151 gn
->kind
= GN_DIRECTORY_NAME
;
2153 gn
->next
= c
->requested_ca
;
2154 c
->requested_ca
= gn
;
2156 c
->got_certrequest
= TRUE
;
2158 DBG(DBG_PARSING
| DBG_CONTROL
,
2159 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2160 DBG_log("requested CA: '%s'", buf
);
2164 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2165 enum_show(&cert_type_names
, cr
->isacr_type
));
2169 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2170 * Note: we may change connections as a result.
2171 * We must be called before SIG or HASH are decoded since we
2172 * may change the peer's RSA key or ID.
2174 static bool decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2176 struct state
*const st
= md
->st
;
2177 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2178 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2179 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2181 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2182 * It talks about the protocol ID and Port fields of the ID
2183 * Payload, but they don't exist as such in Phase 1.
2184 * We use more appropriate names.
2185 * isaid_doi_specific_a is in place of Protocol ID.
2186 * isaid_doi_specific_b is in place of Port.
2187 * Besides, there is no good reason for allowing these to be
2188 * other than 0 in Phase 1.
2190 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2191 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2192 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2194 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2195 "accepted with port_floating NAT-T",
2196 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2198 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2199 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2201 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2203 , IPPROTO_UDP
, IKE_UDP_PORT
2204 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2208 peer
->kind
= id
->isaid_idtype
;
2214 /* failure mode for initaddr is probably inappropriate address length */
2216 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2217 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2222 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2223 , enum_show(&ident_names
, peer
->kind
), ugh
);
2224 /* XXX Could send notification back */
2231 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2233 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2238 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2240 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2241 , enum_show(&ident_names
, peer
->kind
));
2245 /* ??? ought to do some more sanity check, but what? */
2247 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2251 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2253 DBG_dump_chunk("KEY ID:", peer
->name
));
2256 case ID_DER_ASN1_DN
:
2257 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2259 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2263 /* XXX Could send notification back */
2264 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2265 , enum_show(&ident_names
, peer
->kind
));
2272 idtoa(peer
, buf
, sizeof(buf
));
2273 plog("Peer ID is %s: '%s'",
2274 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2277 /* check for certificates */
2282 /* Now that we've decoded the ID payload, let's see if we
2283 * need to switch connections.
2284 * We must not switch horses if we initiated:
2285 * - if the initiation was explicit, we'd be ignoring user's intent
2286 * - if opportunistic, we'll lose our HOLD info
2288 static bool switch_connection(struct msg_digest
*md
, struct id
*peer
,
2291 struct state
*const st
= md
->st
;
2292 struct connection
*c
= st
->st_connection
;
2294 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2295 ? st
->st_peer_pubkey
->issuer
: chunk_empty
;
2300 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2301 DBG_log("peer CA: '%s'", buf
);
2308 if (!same_id(&c
->spd
.that
.id
, peer
))
2310 char expect
[BUF_LEN
]
2313 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2314 idtoa(peer
, found
, sizeof(found
));
2315 loglog(RC_LOG_SERIOUS
2316 , "we require peer to have ID '%s', but peer declares '%s'"
2324 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.that
.ca
, "%none");
2325 DBG_log("required CA: '%s'", buf
);
2328 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2330 loglog(RC_LOG_SERIOUS
2331 , "we don't accept the peer's CA");
2337 struct connection
*r
;
2339 /* check for certificate requests */
2342 r
= refine_host_connection(st
, peer
, peer_ca
);
2344 /* delete the collected certificate requests */
2345 free_generalNames(c
->requested_ca
, TRUE
);
2346 c
->requested_ca
= NULL
;
2352 idtoa(peer
, buf
, sizeof(buf
));
2353 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2360 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2361 DBG_log("offered CA: '%s'", buf
);
2366 /* apparently, r is an improvement on c -- replace */
2369 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2370 if (r
->kind
== CK_TEMPLATE
)
2372 /* instantiate it, filling in peer's ID */
2373 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2374 , c
->spd
.that
.host_port
, NULL
, peer
);
2377 /* copy certificate request info */
2378 r
->got_certrequest
= c
->got_certrequest
;
2380 st
->st_connection
= r
; /* kill reference to c */
2381 set_cur_connection(r
);
2382 connection_discard(c
);
2384 else if (c
->spd
.that
.has_id_wildcards
)
2386 free_id_content(&c
->spd
.that
.id
);
2387 c
->spd
.that
.id
= *peer
;
2388 c
->spd
.that
.has_id_wildcards
= FALSE
;
2389 unshare_id_content(&c
->spd
.that
.id
);
2395 /* Decode the variable part of an ID packet (during Quick Mode).
2396 * This is designed for packets that identify clients, not peers.
2397 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2398 * (1) it is wrong and (2) we use this value for inband signalling.
2400 static bool decode_net_id(struct isakmp_ipsec_id
*id
, pb_stream
*id_pbs
,
2401 ip_subnet
*net
, const char *which
)
2403 const struct af_info
*afi
= NULL
;
2405 /* Note: the following may be a pointer into static memory
2406 * that may be recycled, but only if the type is not known.
2407 * That case is disposed of very early -- in the first switch.
2409 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2411 switch (id
->isaiid_idtype
)
2414 case ID_IPV4_ADDR_SUBNET
:
2415 case ID_IPV4_ADDR_RANGE
:
2416 afi
= &af_inet4_info
;
2419 case ID_IPV6_ADDR_SUBNET
:
2420 case ID_IPV6_ADDR_RANGE
:
2421 afi
= &af_inet6_info
;
2426 /* XXX support more */
2427 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2429 /* XXX Could send notification back */
2433 switch (id
->isaiid_idtype
)
2438 ip_address temp_address
;
2441 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2445 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2446 , which
, idtypename
, ugh
);
2447 /* XXX Could send notification back */
2450 if (isanyaddr(&temp_address
))
2452 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2453 , which
, idtypename
, ip_str(&temp_address
));
2454 /* XXX Could send notification back */
2457 happy(addrtosubnet(&temp_address
, net
));
2458 DBG(DBG_PARSING
| DBG_CONTROL
2459 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2463 case ID_IPV4_ADDR_SUBNET
:
2464 case ID_IPV6_ADDR_SUBNET
:
2466 ip_address temp_address
, temp_mask
;
2469 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2471 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2472 , which
, idtypename
);
2473 /* XXX Could send notification back */
2476 ugh
= initaddr(id_pbs
->cur
2477 , afi
->ia_sz
, afi
->af
, &temp_address
);
2479 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2480 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2482 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2484 if (ugh
== NULL
&& subnetisnone(net
))
2485 ugh
= "contains only anyaddr";
2488 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2489 , which
, idtypename
, ugh
);
2490 /* XXX Could send notification back */
2493 DBG(DBG_PARSING
| DBG_CONTROL
,
2495 char temp_buff
[SUBNETTOT_BUF
];
2497 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2498 DBG_log("%s is subnet %s", which
, temp_buff
);
2503 case ID_IPV4_ADDR_RANGE
:
2504 case ID_IPV6_ADDR_RANGE
:
2506 ip_address temp_address_from
, temp_address_to
;
2509 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2511 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2512 , which
, idtypename
);
2513 /* XXX Could send notification back */
2516 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2518 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2519 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2522 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2523 , which
, idtypename
, ugh
);
2524 /* XXX Could send notification back */
2528 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2529 if (ugh
== NULL
&& subnetisnone(net
))
2530 ugh
= "contains only anyaddr";
2533 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2535 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2536 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2537 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2538 " %s - %s unacceptable: %s"
2539 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2542 DBG(DBG_PARSING
| DBG_CONTROL
,
2544 char temp_buff
[SUBNETTOT_BUF
];
2546 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2547 DBG_log("%s is subnet %s (received as range)"
2548 , which
, temp_buff
);
2554 /* set the port selector */
2555 setportof(htons(id
->isaiid_port
), &net
->addr
);
2557 DBG(DBG_PARSING
| DBG_CONTROL
,
2558 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2564 /* like decode, but checks that what is received matches what was sent */
2565 static bool check_net_id(struct isakmp_ipsec_id
*id
, pb_stream
*id_pbs
,
2566 u_int8_t
*protoid
, u_int16_t
*port
, ip_subnet
*net
,
2571 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2574 if (!samesubnet(net
, &net_temp
)
2575 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2577 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2584 * look for the existence of a non-expiring preloaded public key
2586 static bool has_preloaded_public_key(struct state
*st
)
2588 struct connection
*c
= st
->st_connection
;
2590 /* do not consider rw connections since
2591 * the peer's identity must be known
2593 if (c
->kind
== CK_PERMANENT
)
2597 /* look for a matching RSA public key */
2598 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2600 pubkey_t
*key
= p
->key
;
2601 key_type_t type
= key
->public_key
->get_type(key
->public_key
);
2603 if (type
== KEY_RSA
&& same_id(&c
->spd
.that
.id
, &key
->id
) &&
2604 key
->until_time
== UNDEFINED_TIME
)
2606 /* found a preloaded public key */
2615 * Produce the new key material of Quick Mode.
2616 * RFC 2409 "IKE" section 5.5
2617 * specifies how this is to be done.
2619 static void compute_proto_keymat(struct state
*st
, u_int8_t protoid
,
2620 struct ipsec_proto_info
*pi
)
2622 size_t needed_len
= 0; /* bytes of keying material needed */
2624 /* Add up the requirements for keying material
2625 * (It probably doesn't matter if we produce too much!)
2629 case PROTO_IPSEC_ESP
:
2630 switch (pi
->attrs
.transid
)
2636 needed_len
= DES_CBC_BLOCK_SIZE
;
2639 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2642 #ifndef NO_KERNEL_ALG
2643 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2644 /* XXX: check key_len "coupling with kernel.c's */
2645 if (pi
->attrs
.key_len
) {
2646 needed_len
=pi
->attrs
.key_len
/8;
2647 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2648 "key_len=%d from peer",
2654 bad_case(pi
->attrs
.transid
);
2657 #ifndef NO_KERNEL_ALG
2658 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2659 "needed_len (after ESP enc)=%d",
2661 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2662 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2665 switch (pi
->attrs
.auth
)
2667 case AUTH_ALGORITHM_NONE
:
2669 case AUTH_ALGORITHM_HMAC_MD5
:
2670 needed_len
+= HMAC_MD5_KEY_LEN
;
2672 case AUTH_ALGORITHM_HMAC_SHA1
:
2673 needed_len
+= HMAC_SHA1_KEY_LEN
;
2675 case AUTH_ALGORITHM_DES_MAC
:
2677 bad_case(pi
->attrs
.auth
);
2679 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2680 "needed_len (after ESP auth)=%d",
2684 case PROTO_IPSEC_AH
:
2685 switch (pi
->attrs
.transid
)
2688 needed_len
= HMAC_MD5_KEY_LEN
;
2691 needed_len
= HMAC_SHA1_KEY_LEN
;
2694 bad_case(pi
->attrs
.transid
);
2702 pi
->keymat_len
= needed_len
;
2704 /* Allocate space for the keying material. Although only needed_len bytes
2705 * are desired, we must round up to a multiple of hash_size
2706 * so that our buffer isn't overrun.
2709 size_t needed_space
; /* space needed for keying material (rounded up) */
2710 size_t i
, prf_block_size
;
2711 chunk_t protoid_chunk
= chunk_from_thing(protoid
);
2712 chunk_t spi_our
= chunk_from_thing(pi
->our_spi
);
2713 chunk_t spi_peer
= chunk_from_thing(pi
->attrs
.spi
);
2714 pseudo_random_function_t prf_alg
;
2715 prf_t
*prf_our
, *prf_peer
;
2717 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
2718 prf_our
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
2719 prf_peer
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
2720 prf_our
->set_key(prf_our
, st
->st_skeyid_d
);
2721 prf_peer
->set_key(prf_peer
, st
->st_skeyid_d
);
2722 prf_block_size
= prf_our
->get_block_size(prf_our
);
2724 needed_space
= needed_len
+ pad_up(needed_len
, prf_block_size
);
2725 replace(pi
->our_keymat
, malloc(needed_space
));
2726 replace(pi
->peer_keymat
, malloc(needed_space
));
2730 char *keymat_i_our
= pi
->our_keymat
+ i
;
2731 char *keymat_i_peer
= pi
->peer_keymat
+ i
;
2732 chunk_t keymat_our
= { keymat_i_our
, prf_block_size
};
2733 chunk_t keymat_peer
= { keymat_i_peer
, prf_block_size
};
2735 if (st
->st_shared
.ptr
!= NULL
)
2737 /* PFS: include the g^xy */
2738 prf_our
->get_bytes(prf_our
, st
->st_shared
, NULL
);
2739 prf_peer
->get_bytes(prf_peer
, st
->st_shared
, NULL
);
2741 prf_our
->get_bytes(prf_our
, protoid_chunk
, NULL
);
2742 prf_peer
->get_bytes(prf_peer
, protoid_chunk
, NULL
);
2744 prf_our
->get_bytes(prf_our
, spi_our
, NULL
);
2745 prf_peer
->get_bytes(prf_peer
, spi_peer
, NULL
);
2747 prf_our
->get_bytes(prf_our
, st
->st_ni
, NULL
);
2748 prf_peer
->get_bytes(prf_peer
, st
->st_ni
, NULL
);
2750 prf_our
->get_bytes(prf_our
, st
->st_nr
, keymat_i_our
);
2751 prf_peer
->get_bytes(prf_peer
, st
->st_nr
, keymat_i_peer
);
2753 i
+= prf_block_size
;
2754 if (i
>= needed_space
)
2759 /* more keying material needed: prepare to go around again */
2760 prf_our
->get_bytes(prf_our
, keymat_our
, NULL
);
2761 prf_peer
->get_bytes(prf_peer
, keymat_peer
, NULL
);
2763 prf_our
->destroy(prf_our
);
2764 prf_peer
->destroy(prf_peer
);
2767 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2768 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2771 static void compute_keymats(struct state
*st
)
2773 if (st
->st_ah
.present
)
2774 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2775 if (st
->st_esp
.present
)
2776 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2779 /* State Transition Functions.
2781 * The definition of state_microcode_table in demux.c is a good
2782 * overview of these routines.
2784 * - Called from process_packet; result handled by complete_state_transition
2785 * - struct state_microcode member "processor" points to these
2786 * - these routine definitionss are in state order
2787 * - these routines must be restartable from any point of error return:
2788 * beware of memory allocated before any error.
2789 * - output HDR is usually emitted by process_packet (if state_microcode
2790 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2792 * The transition functions' functions include:
2793 * - process and judge payloads
2794 * - update st_iv (result of decryption is in st_new_iv)
2795 * - build reply packet
2798 /* Handle a Main Mode Oakley first packet (responder side).
2801 stf_status
main_inI1_outR1(struct msg_digest
*md
)
2803 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2805 struct connection
*c
;
2806 struct isakmp_proposal proposal
;
2807 pb_stream proposal_pbs
;
2809 u_int32_t ipsecdoisit
;
2810 lset_t policy
= LEMPTY
;
2811 int vids_to_send
= 0;
2813 /* We preparse the peer's proposal in order to determine
2814 * the requested authentication policy (RSA or PSK)
2816 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2817 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2819 backup_pbs(&proposal_pbs
);
2820 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2821 , proposal
.isap_notrans
, &policy
));
2822 restore_pbs(&proposal_pbs
);
2824 /* We are only considering candidate connections that match
2825 * the requested authentication policy (RSA or PSK)
2827 c
= find_host_connection(&md
->iface
->addr
, pluto_port
2828 , &md
->sender
, md
->sender_port
, policy
);
2830 if (c
== NULL
&& md
->iface
->ike_float
)
2832 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
2833 , &md
->sender
, md
->sender_port
, policy
);
2838 /* See if a wildcarded connection can be found.
2839 * We cannot pick the right connection, so we're making a guess.
2840 * All Road Warrior connections are fair game:
2841 * we pick the first we come across (if any).
2842 * If we don't find any, we pick the first opportunistic
2843 * with the smallest subnet that includes the peer.
2844 * There is, of course, no necessary relationship between
2845 * an Initiator's address and that of its client,
2846 * but Food Groups kind of assumes one.
2849 struct connection
*d
;
2851 d
= find_host_connection(&md
->iface
->addr
2852 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
2854 for (; d
!= NULL
; d
= d
->hp_next
)
2856 if (d
->kind
== CK_GROUP
)
2862 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
2864 /* must be Road Warrior: we have a winner */
2869 /* Opportunistic or Shunt: pick tightest match */
2870 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
2871 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
2879 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
2880 " but no connection has been authorized%s%s"
2881 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
2882 , (policy
!= LEMPTY
) ?
" with policy=" : ""
2883 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
2884 /* XXX notification is in order! */
2887 else if (c
->kind
!= CK_TEMPLATE
)
2889 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
2890 " but \"%s\" forbids connection"
2891 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
2892 /* XXX notification is in order! */
2897 /* Create a temporary connection that is a copy of this one.
2898 * His ID isn't declared yet.
2900 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
2903 else if (c
->kind
== CK_TEMPLATE
)
2905 /* Create an instance
2906 * This is a rare case: wildcard peer ID but static peer IP address
2908 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
2912 md
->st
= st
= new_state();
2913 st
->st_connection
= c
;
2914 set_cur_state(st
); /* (caller will reset cur_state) */
2915 st
->st_try
= 0; /* not our job to try again from start */
2916 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
2918 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
2919 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
2921 insert_state(st
); /* needs cookies, connection, and msgid (0) */
2923 st
->st_doi
= ISAKMP_DOI_IPSEC
;
2924 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
2926 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
2928 plog("responding to Main Mode from unknown peer %s:%u"
2929 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
2931 else if (c
->kind
== CK_INSTANCE
)
2933 plog("responding to Main Mode from unknown peer %s"
2934 , ip_str(&c
->spd
.that
.host_addr
));
2938 plog("responding to Main Mode");
2941 /* parse_isakmp_sa also spits out a winning SA into our reply,
2942 * so we have to build our md->reply and emit HDR before calling it.
2945 /* determine how many Vendor ID payloads we will be sending */
2948 if (SEND_CISCO_UNITY_VID
)
2954 /* always send DPD Vendor ID */
2956 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
2960 * We can't leave this to comm_handle() because we must
2961 * fill in the cookie.
2964 struct isakmp_hdr r_hdr
= md
->hdr
;
2966 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
2967 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
2968 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
2969 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
2970 return STF_INTERNAL_ERROR
;
2973 /* start of SA out */
2975 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
2977 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
2979 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
2980 return STF_INTERNAL_ERROR
;
2983 /* SA body in and out */
2984 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
2985 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
2987 /* if enabled send Pluto Vendor ID */
2990 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
2991 , &md
->rbody
, VID_STRONGSWAN
))
2993 return STF_INTERNAL_ERROR
;
2997 /* if enabled send Cisco Unity Vendor ID */
2998 if (SEND_CISCO_UNITY_VID
)
3000 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3001 , &md
->rbody
, VID_CISCO_UNITY
))
3003 return STF_INTERNAL_ERROR
;
3008 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3012 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3013 , &md
->rbody
, VID_OPENPGP
))
3015 return STF_INTERNAL_ERROR
;
3019 /* Announce our ability to do eXtended AUTHentication to the peer */
3022 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3023 , &md
->rbody
, VID_MISC_XAUTH
))
3025 return STF_INTERNAL_ERROR
;
3029 /* Announce our ability to do Dead Peer Detection to the peer */
3030 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3031 , &md
->rbody
, VID_MISC_DPD
))
3033 return STF_INTERNAL_ERROR
;
3036 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3038 /* reply if NAT-Traversal draft is supported */
3039 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3041 if (st
->nat_traversal
3042 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3043 , &md
->rbody
, md
->nat_traversal_vid
))
3045 return STF_INTERNAL_ERROR
;
3049 close_message(&md
->rbody
);
3051 /* save initiator SA for HASH */
3052 free(st
->st_p1isa
.ptr
);
3053 st
->st_p1isa
= chunk_create(sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
));
3054 st
->st_p1isa
= chunk_clone(st
->st_p1isa
);
3059 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3060 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3062 * The following are not yet implemented:
3063 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3064 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3065 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3067 * We must verify that the proposal received matches one we sent.
3069 stf_status
main_inR1_outI2(struct msg_digest
*md
)
3071 struct state
*const st
= md
->st
;
3073 u_int8_t np
= ISAKMP_NEXT_NONE
;
3075 /* verify echoed SA */
3077 u_int32_t ipsecdoisit
;
3078 pb_stream proposal_pbs
;
3079 struct isakmp_proposal proposal
;
3080 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3082 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3083 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3084 if (proposal
.isap_notrans
!= 1)
3086 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3087 , (unsigned)proposal
.isap_notrans
);
3088 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3090 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3091 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3094 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3096 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3097 plog("enabling possible NAT-traversal with method %s"
3098 , bitnamesof(natt_type_bitnames
, st
->nat_traversal
));
3100 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3102 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3103 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3106 /**************** build output packet HDR;KE;Ni ****************/
3109 * We can't leave this to comm_handle() because the isa_np
3110 * depends on the type of Auth (eventually).
3112 echo_hdr(md
, FALSE
, ISAKMP_NEXT_KE
);
3115 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_oakley
.group
3116 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3117 return STF_INTERNAL_ERROR
;
3121 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
3122 , (cur_debugging
& IMPAIR_BUST_MI2
)? ISAKMP_NEXT_VID
: np
, "Ni"))
3123 return STF_INTERNAL_ERROR
;
3125 if (cur_debugging
& IMPAIR_BUST_MI2
)
3127 /* generate a pointless large VID payload to push message over MTU */
3130 if (!out_generic(np
, &isakmp_vendor_id_desc
, &md
->rbody
, &vid_pbs
))
3131 return STF_INTERNAL_ERROR
;
3132 if (!out_zero(1500 /*MTU?*/, &vid_pbs
, "Filler VID"))
3133 return STF_INTERNAL_ERROR
;
3134 close_output_pbs(&vid_pbs
);
3138 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
, np
, "Ni"))
3139 return STF_INTERNAL_ERROR
;
3142 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3144 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE
, &md
->rbody
, md
))
3145 return STF_INTERNAL_ERROR
;
3148 /* finish message */
3149 close_message(&md
->rbody
);
3151 /* Reinsert the state, using the responder cookie we just received */
3153 memcpy(st
->st_rcookie
, md
->hdr
.isa_rcookie
, COOKIE_SIZE
);
3154 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3160 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3162 * The following are not yet implemented:
3163 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3164 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3166 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3167 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3169 stf_status
main_inI2_outR2(struct msg_digest
*md
)
3171 struct state
*const st
= md
->st
;
3172 pb_stream
*keyex_pbs
= &md
->chain
[ISAKMP_NEXT_KE
]->pbs
;
3174 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3175 bool RSA_auth
= st
->st_oakley
.auth
== OAKLEY_RSA_SIG
3176 || st
->st_oakley
.auth
== XAUTHInitRSA
3177 || st
->st_oakley
.auth
== XAUTHRespRSA
;
3178 bool send_cr
= !no_cr_send
&& RSA_auth
&& !has_preloaded_public_key(st
);
3180 u_int8_t np
= ISAKMP_NEXT_NONE
;