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>
38 #include "constants.h"
47 #include "smartcard.h"
48 #include "connections.h"
51 #include "demux.h" /* needs packet.h */
52 #include "adns.h" /* needs <resolv.h> */
53 #include "dnskey.h" /* needs keys.h and adns.h */
60 #include "ipsec_doi.h" /* needs demux.h and state.h */
68 #include "kernel_alg.h"
69 #include "nat_traversal.h"
73 * are we sending Pluto's Vendor ID?
76 #define SEND_PLUTO_VID 1
78 #define SEND_PLUTO_VID 0
79 #endif /* !VENDORID */
82 * are we sending an XAUTH VID?
85 #define SEND_XAUTH_VID 1
86 #else /* !XAUTH_VID */
87 #define SEND_XAUTH_VID 0
88 #endif /* !XAUTH_VID */
91 * are we sending a Cisco Unity VID?
94 #define SEND_CISCO_UNITY_VID 1
95 #else /* !CISCO_QUIRKS */
96 #define SEND_CISCO_UNITY_VID 0
97 #endif /* !CISCO_QUIRKS */
99 /* MAGIC: perform f, a function that returns notification_t
100 * and return from the ENCLOSING stf_status returning function if it fails.
102 #define RETURN_STF_FAILURE(f) \
103 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
105 /* create output HDR as replica of input HDR */
107 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
109 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
111 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
113 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
114 /* some day, we may have to set r_hdr.isa_version */
116 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
117 impossible(); /* surely must have room and be well-formed */
120 /* Compute DH shared secret from our local secret and the peer's public value.
121 * We make the leap that the length should be that of the group
122 * (see quoted passage at start of ACCEPT_KE).
124 static void compute_dh_shared(struct state
*st
, const chunk_t g
)
127 st
->st_dh
->set_other_public_value(st
->st_dh
, g
);
128 st
->st_dh
->get_shared_secret(st
->st_dh
, &st
->st_shared
);
129 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
132 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
133 * the corresponding public value (g). This is emitted as a KE payload.
135 static bool build_and_ship_KE(struct state
*st
, chunk_t
*g
,
136 const struct dh_desc
*group
,
137 pb_stream
*outs
, u_int8_t np
)
139 if (st
->st_dh
== NULL
)
141 st
->st_dh
= lib
->crypto
->create_dh(lib
->crypto
, group
->algo_id
);
142 if (st
->st_dh
== NULL
)
144 plog("Diffie Hellman group %N is not available",
145 diffie_hellman_group_names
, group
->algo_id
);
149 st
->st_dh
->get_my_public_value(st
->st_dh
, g
);
151 DBG_dump_chunk("Public DH value sent:\n", *g
)
153 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
158 * Check and accept DH public value (Gi or Gr) from peer's message.
159 * According to RFC2409 "The Internet key exchange (IKE)" 5:
160 * The Diffie-Hellman public value passed in a KE payload, in either
161 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
162 * Diffie-Hellman group enforced, if necessary, by pre-pending the
165 static notification_t
accept_KE(chunk_t
*dest
, const char *val_name
,
166 const struct dh_desc
*gr
,
169 if (pbs_left(pbs
) != gr
->ke_size
)
171 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
172 , (unsigned) pbs_left(pbs
), gr
->ke_size
);
173 /* XXX Could send notification back */
174 return INVALID_KEY_INFORMATION
;
177 *dest
= chunk_create(pbs
->cur
, pbs_left(pbs
));
178 *dest
= chunk_clone(*dest
);
179 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
180 return NOTHING_WRONG
;
185 * Check and accept optional Quick Mode KE payload for PFS.
186 * Extends ACCEPT_PFS to check whether KE is allowed or required.
188 static notification_t
accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
,
189 const char *val_name
, const char *msg_name
)
191 struct state
*st
= md
->st
;
192 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
196 if (st
->st_pfs_group
!= NULL
)
198 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
199 return INVALID_KEY_INFORMATION
;
204 if (st
->st_pfs_group
== NULL
)
206 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
208 return INVALID_KEY_INFORMATION
;
210 if (ke_pd
->next
!= NULL
)
212 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
213 return INVALID_KEY_INFORMATION
; /* ??? */
215 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
217 return NOTHING_WRONG
;
220 static bool build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
,
226 *n
= chunk_create(malloc(DEFAULT_NONCE_SIZE
), DEFAULT_NONCE_SIZE
);
227 rng
= lib
->crypto
->create_rng(lib
->crypto
, RNG_WEAK
);
228 rng
->get_bytes(rng
, DEFAULT_NONCE_SIZE
, n
->ptr
);
230 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
233 static bool collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
235 struct connection
*d
= find_host_connection(&md
->iface
->addr
236 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
238 for (; d
!= NULL
; d
= d
->hp_next
)
240 /* must be a road warrior connection */
241 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
242 && d
->spd
.that
.ca
.ptr
!= NULL
)
245 bool new_entry
= TRUE
;
247 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
249 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
257 gn
= malloc_thing(generalName_t
);
258 gn
->kind
= GN_DIRECTORY_NAME
;
259 gn
->name
= d
->spd
.that
.ca
;
268 static bool build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
,
272 struct isakmp_cr cr_hd
;
274 cr_hd
.isacr_type
= type
;
276 /* build CR header */
277 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
282 /* build CR body containing the distinguished name of the CA */
283 if (!out_chunk(ca
, &cr_pbs
, "CA"))
286 close_output_pbs(&cr_pbs
);
290 /* Send a notification to the peer. We could decide
291 * whether to send the notification, based on the type and the
292 * destination, if we care to.
294 static void send_notification(struct state
*sndst
, u_int16_t type
,
295 struct state
*encst
, msgid_t msgid
,
296 u_char
*icookie
, u_char
*rcookie
,
297 u_char
*spi
, size_t spisize
, u_char protoid
)
300 pb_stream pbs
, r_hdr_pbs
;
301 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
302 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
304 passert((sndst
) && (sndst
->st_connection
));
306 plog("sending %snotification %s to %s:%u"
307 , encst ?
"encrypted " : ""
308 , enum_name(¬ification_names
, type
)
309 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
310 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
312 memset(buffer
, 0, sizeof(buffer
));
313 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
317 struct isakmp_hdr hdr
;
319 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
320 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
321 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
322 hdr
.isa_msgid
= msgid
;
323 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
325 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
327 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
328 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
332 /* HASH -- value to be filled later */
336 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
339 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
341 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
343 close_output_pbs(&hash_pbs
);
344 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
347 /* Notification Payload */
350 struct isakmp_notification isan
;
352 isan
.isan_doi
= ISAKMP_DOI_IPSEC
;
353 isan
.isan_np
= ISAKMP_NEXT_NONE
;
354 isan
.isan_type
= type
;
355 isan
.isan_spisize
= spisize
;
356 isan
.isan_protoid
= protoid
;
358 if (!out_struct(&isan
, &isakmp_notification_desc
, &r_hdr_pbs
, ¬_pbs
)
359 || !out_raw(spi
, spisize
, ¬_pbs
, "spi"))
361 close_output_pbs(¬_pbs
);
364 /* calculate hash value and patch into Hash Payload */
367 chunk_t msgid_chunk
= chunk_from_thing(msgid
);
368 chunk_t msg_chunk
= { r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
};
369 pseudo_random_function_t prf_alg
;
372 prf_alg
= oakley_to_prf(encst
->st_oakley
.hash
);
373 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
374 prf
->set_key(prf
, encst
->st_skeyid_a
);
375 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
376 prf
->get_bytes(prf
, msg_chunk
, r_hashval
);
379 DBG_log("HASH computed:");
380 DBG_dump("", r_hashval
, prf
->get_block_size(prf
));
385 /* Encrypt message (preserve st_iv and st_new_iv) */
388 u_char old_iv
[MAX_DIGEST_LEN
];
389 u_char new_iv
[MAX_DIGEST_LEN
];
391 u_int old_iv_len
= encst
->st_iv_len
;
392 u_int new_iv_len
= encst
->st_new_iv_len
;
394 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
397 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
398 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
400 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
402 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
403 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
405 init_phase2_iv(encst
, &msgid
);
406 if (!encrypt_message(&r_hdr_pbs
, encst
))
409 /* restore preserved st_iv and st_new_iv */
410 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
411 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
412 encst
->st_iv_len
= old_iv_len
;
413 encst
->st_new_iv_len
= new_iv_len
;
417 close_output_pbs(&r_hdr_pbs
);
420 /* Send packet (preserve st_tpacket) */
422 chunk_t saved_tpacket
= sndst
->st_tpacket
;
424 sndst
->st_tpacket
= chunk_create(pbs
.start
, pbs_offset(&pbs
));
425 send_packet(sndst
, "ISAKMP notify");
426 sndst
->st_tpacket
= saved_tpacket
;
430 void send_notification_from_state(struct state
*st
, enum state_kind state
,
437 if (state
== STATE_UNDEFINED
)
438 state
= st
->st_state
;
442 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
443 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
)))
445 loglog(RC_LOG_SERIOUS
,
446 "no Phase1 state for Quick mode notification");
449 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
450 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
452 else if (IS_ISAKMP_ENCRYPTED(state
) && st
->st_enc_key
.ptr
!= NULL
)
454 send_notification(st
, type
, st
, generate_msgid(st
),
455 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
459 /* no ISAKMP SA established - don't encrypt notification */
460 send_notification(st
, type
, NULL
, 0,
461 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
465 void send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
468 * Create a dummy state to be able to use send_packet in
472 * st_connection->that.host_addr
473 * st_connection->that.host_port
474 * st_connection->interface
477 struct connection cnx
;
481 memset(&st
, 0, sizeof(st
));
482 memset(&cnx
, 0, sizeof(cnx
));
483 st
.st_connection
= &cnx
;
484 cnx
.spd
.that
.host_addr
= md
->sender
;
485 cnx
.spd
.that
.host_port
= md
->sender_port
;
486 cnx
.interface
= md
->iface
;
488 send_notification(&st
, type
, NULL
, 0,
489 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
492 /* Send a Delete Notification to announce deletion of ISAKMP SA or
493 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
494 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
496 void send_delete(struct state
*st
)
503 ip_said said
[EM_MAXRELSPIS
];
506 *r_hashval
, /* where in reply to jam hash value */
507 *r_hash_start
; /* start of what is to be hashed */
508 bool isakmp_sa
= FALSE
;
510 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
512 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
515 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
519 if (st
->st_ah
.present
)
521 ns
->spi
= st
->st_ah
.our_spi
;
522 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
523 ns
->proto
= PROTO_IPSEC_AH
;
526 if (st
->st_esp
.present
)
528 ns
->spi
= st
->st_esp
.our_spi
;
529 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
530 ns
->proto
= PROTO_IPSEC_ESP
;
534 passert(ns
!= said
); /* there must be some SAs to delete */
536 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
543 return; /* nothing to do */
546 msgid
= generate_msgid(p1st
);
549 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
553 struct isakmp_hdr hdr
;
555 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
556 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
557 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
558 hdr
.isa_msgid
= msgid
;
559 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
560 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
561 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
562 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
566 /* HASH -- value to be filled later */
570 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
572 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
573 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
575 close_output_pbs(&hash_pbs
);
576 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
579 /* Delete Payloads */
583 struct isakmp_delete isad
;
584 u_char isakmp_spi
[2*COOKIE_SIZE
];
586 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
587 isad
.isad_np
= ISAKMP_NEXT_NONE
;
588 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
589 isad
.isad_protoid
= PROTO_ISAKMP
;
592 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
593 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
595 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
596 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
598 close_output_pbs(&del_pbs
);
606 struct isakmp_delete isad
;
609 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
610 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
611 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
612 isad
.isad_protoid
= ns
->proto
;
615 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
616 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
618 close_output_pbs(&del_pbs
);
622 /* calculate hash value and patch into Hash Payload */
624 chunk_t msgid_chunk
= chunk_from_thing(msgid
);
625 chunk_t msg_chunk
= { r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
};
626 pseudo_random_function_t prf_alg
;
629 prf_alg
= oakley_to_prf(p1st
->st_oakley
.hash
);
630 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
631 prf
->set_key(prf
, p1st
->st_skeyid_a
);
632 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
633 prf
->get_bytes(prf
, msg_chunk
, r_hashval
);
636 DBG_log("HASH(1) computed:");
637 DBG_dump("", r_hashval
, prf
->get_block_size(prf
));
643 /* Do a dance to avoid needing a new state object.
644 * We use the Phase 1 State. This is the one with right
646 * The tricky bits are:
647 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
648 * - we need to preserve (save/restore) st_tpacket.
651 u_char old_iv
[MAX_DIGEST_LEN
];
652 chunk_t saved_tpacket
= p1st
->st_tpacket
;
654 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
655 init_phase2_iv(p1st
, &msgid
);
657 if (!encrypt_message(&r_hdr_pbs
, p1st
))
660 p1st
->st_tpacket
= chunk_create(reply_pbs
.start
, pbs_offset(&reply_pbs
));
661 send_packet(p1st
, "delete notify");
662 p1st
->st_tpacket
= saved_tpacket
;
664 /* get back old IV for this state */
665 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
669 void accept_delete(struct state
*st
, struct msg_digest
*md
,
670 struct payload_digest
*p
)
672 struct isakmp_delete
*d
= &(p
->payload
.delete);
678 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
682 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
684 /* can't happen (if msg is encrypt), but just to be sure */
685 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
686 "ISAKMP SA not established");
690 if (d
->isad_nospi
== 0)
692 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
696 switch (d
->isad_protoid
)
699 sizespi
= 2 * COOKIE_SIZE
;
702 case PROTO_IPSEC_ESP
:
703 sizespi
= sizeof(ipsec_spi_t
);
706 /* nothing interesting to delete */
709 loglog(RC_LOG_SERIOUS
710 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
711 , enum_show(&protocol_names
, d
->isad_protoid
));
715 if (d
->isad_spisize
!= sizespi
)
717 loglog(RC_LOG_SERIOUS
718 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
719 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
723 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
725 loglog(RC_LOG_SERIOUS
726 , "ignoring Delete SA payload: invalid payload size");
730 for (i
= 0; i
< d
->isad_nospi
; i
++)
732 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
734 if (d
->isad_protoid
== PROTO_ISAKMP
)
739 struct state
*dst
= find_state(spi
/*iCookie*/
740 , spi
+COOKIE_SIZE
/*rCookie*/
741 , &st
->st_connection
->spd
.that
.host_addr
746 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
747 "ISAKMP SA not found (maybe expired)");
749 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
751 /* we've not authenticated the relevant identities */
752 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
753 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
757 struct connection
*oldc
;
759 oldc
= cur_connection
;
760 set_cur_connection(dst
->st_connection
);
762 if (nat_traversal_enabled
)
763 nat_traversal_change_port_lookup(md
, dst
);
765 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
766 "deleting ISAKMP State #%lu", dst
->st_serialno
);
768 set_cur_connection(oldc
);
777 struct state
*dst
= find_phase2_state_to_delete(st
779 , *(ipsec_spi_t
*)spi
/* network order */
784 loglog(RC_LOG_SERIOUS
785 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
786 , enum_show(&protocol_names
, d
->isad_protoid
)
787 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
788 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
792 struct connection
*rc
= dst
->st_connection
;
793 struct connection
*oldc
;
795 oldc
= cur_connection
;
796 set_cur_connection(rc
);
798 if (nat_traversal_enabled
)
799 nat_traversal_change_port_lookup(md
, dst
);
801 if (rc
->newest_ipsec_sa
== dst
->st_serialno
802 && (rc
->policy
& POLICY_UP
))
804 /* Last IPSec SA for a permanent connection that we
805 * have initiated. Replace it in a few seconds.
807 * Useful if the other peer is rebooting.
809 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
810 if (dst
->st_event
!= NULL
811 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
812 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
814 /* Patch from Angus Lees to ignore retransmited
817 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
818 "already replacing IPSEC State #%lu in %d seconds"
819 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
823 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
824 "replace IPSEC State #%lu in %d seconds"
825 , dst
->st_serialno
, DELETE_SA_DELAY
);
826 dst
->st_margin
= DELETE_SA_DELAY
;
828 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
833 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
834 "deleting IPSEC State #%lu"
835 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
840 /* reset connection */
841 set_cur_connection(oldc
);
847 /* The whole message must be a multiple of 4 octets.
848 * I'm not sure where this is spelled out, but look at
849 * rfc2408 3.6 Transform Payload.
850 * Note: it talks about 4 BYTE boundaries!
852 void close_message(pb_stream
*pbs
)
854 size_t padding
= pad_up(pbs_offset(pbs
), 4);
857 (void) out_zero(padding
, pbs
, "message padding");
858 close_output_pbs(pbs
);
861 /* Initiate an Oakley Main Mode exchange.
863 * Note: this is not called from demux.c
866 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
867 , lset_t policy
, unsigned long try)
869 struct state
*st
= new_state();
870 pb_stream reply
; /* not actually a reply, but you know what I mean */
873 int vids_to_send
= 0;
875 /* set up new state */
876 st
->st_connection
= c
;
877 set_cur_state(st
); /* we must reset before exit */
878 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
879 st
->st_whack_sock
= whack_sock
;
881 st
->st_state
= STATE_MAIN_I1
;
883 /* determine how many Vendor ID payloads we will be sending */
886 if (SEND_CISCO_UNITY_VID
)
888 if (c
->spd
.this.cert
.type
== CERT_PGP
)
892 /* always send DPD Vendor ID */
894 if (nat_traversal_enabled
)
897 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
899 insert_state(st
); /* needs cookies, connection, and msgid (0) */
901 if (HAS_IPSEC_POLICY(policy
))
902 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
903 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
905 if (predecessor
== NULL
)
906 plog("initiating Main Mode");
908 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
911 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
915 struct isakmp_hdr hdr
;
917 zero(&hdr
); /* default to 0 */
918 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
919 hdr
.isa_np
= ISAKMP_NEXT_SA
;
920 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
921 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
922 /* R-cookie, flags and MessageID are left zero */
924 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
927 return STF_INTERNAL_ERROR
;
933 u_char
*sa_start
= rbody
.cur
;
935 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
936 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
939 return STF_INTERNAL_ERROR
;
942 /* save initiator SA for later HASH */
943 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
944 st
->st_p1isa
= chunk_create(sa_start
, rbody
.cur
- sa_start
);
945 st
->st_p1isa
= chunk_clone(st
->st_p1isa
);
948 /* if enabled send Pluto Vendor ID */
951 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
952 , &rbody
, VID_STRONGSWAN
))
955 return STF_INTERNAL_ERROR
;
959 /* if enabled send Cisco Unity Vendor ID */
960 if (SEND_CISCO_UNITY_VID
)
962 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
963 , &rbody
, VID_CISCO_UNITY
))
966 return STF_INTERNAL_ERROR
;
969 /* if we have an OpenPGP certificate we assume an
970 * OpenPGP peer and have to send the Vendor ID
972 if (c
->spd
.this.cert
.type
== CERT_PGP
)
974 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
975 , &rbody
, VID_OPENPGP
))
978 return STF_INTERNAL_ERROR
;
982 /* Announce our ability to do eXtended AUTHentication to the peer */
985 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
986 , &rbody
, VID_MISC_XAUTH
))
989 return STF_INTERNAL_ERROR
;
993 /* Announce our ability to do Dead Peer Detection to the peer */
995 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
996 , &rbody
, VID_MISC_DPD
))
999 return STF_INTERNAL_ERROR
;
1003 if (nat_traversal_enabled
)
1005 /* Add supported NAT-Traversal VID */
1006 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1010 return STF_INTERNAL_ERROR
;
1014 close_message(&rbody
);
1015 close_output_pbs(&reply
);
1016 st
->st_tpacket
= chunk_create(reply
.start
, pbs_offset(&reply
));
1017 st
->st_tpacket
= chunk_clone(st
->st_tpacket
);
1021 send_packet(st
, "main_outI1");
1023 /* Set up a retransmission event, half a minute henceforth */
1025 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1027 if (predecessor
!= NULL
)
1029 update_pending(predecessor
, st
);
1030 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1031 , "%s: initiate, replacing #%lu"
1032 , enum_name(&state_names
, st
->st_state
)
1033 , predecessor
->st_serialno
);
1037 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1038 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1044 void ipsecdoi_initiate(int whack_sock
, struct connection
*c
, lset_t policy
,
1045 unsigned long try, so_serial_t replacing
)
1047 /* If there's already an ISAKMP SA established, use that and
1048 * go directly to Quick Mode. We are even willing to use one
1049 * that is still being negotiated, but only if we are the Initiator
1050 * (thus we can be sure that the IDs are not going to change;
1051 * other issues around intent might matter).
1052 * Note: there is no way to initiate with a Road Warrior.
1054 struct state
*st
= find_phase1_state(c
1055 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1059 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1061 else if (HAS_IPSEC_POLICY(policy
))
1063 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1065 /* leave our Phase 2 negotiation pending */
1066 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1070 /* ??? we assume that peer_nexthop_sin isn't important:
1071 * we already have it from when we negotiated the ISAKMP SA!
1072 * It isn't clear what to do with the error return.
1074 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1079 close_any(whack_sock
);
1083 /* Replace SA with a fresh one that is similar
1085 * Shares some logic with ipsecdoi_initiate, but not the same!
1086 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1087 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1088 * ISAKMP SA if needed.
1089 * - duplicate whack fd, if live.
1090 * Does not delete the old state -- someone else will do that.
1092 void ipsecdoi_replace(struct state
*st
, unsigned long try)
1094 int whack_sock
= dup_any(st
->st_whack_sock
);
1095 lset_t policy
= st
->st_policy
;
1097 if (IS_PHASE1(st
->st_state
))
1099 passert(!HAS_IPSEC_POLICY(policy
));
1100 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1104 /* Add features of actual old state to policy. This ensures
1105 * that rekeying doesn't downgrade security. I admit that
1106 * this doesn't capture everything.
1108 if (st
->st_pfs_group
!= NULL
)
1109 policy
|= POLICY_PFS
;
1110 if (st
->st_ah
.present
)
1112 policy
|= POLICY_AUTHENTICATE
;
1113 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1114 policy
|= POLICY_TUNNEL
;
1116 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1118 policy
|= POLICY_ENCRYPT
;
1119 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1120 policy
|= POLICY_TUNNEL
;
1122 if (st
->st_ipcomp
.present
)
1124 policy
|= POLICY_COMPRESS
;
1125 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1126 policy
|= POLICY_TUNNEL
;
1128 passert(HAS_IPSEC_POLICY(policy
));
1129 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1134 /* SKEYID for preshared keys.
1135 * See draft-ietf-ipsec-ike-01.txt 4.1
1137 static bool skeyid_preshared(struct state
*st
)
1139 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1143 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1148 pseudo_random_function_t prf_alg
;
1151 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1152 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1155 loglog(RC_LOG_SERIOUS
, "%N not available to compute skeyid",
1156 pseudo_random_function_names
, prf_alg
);
1159 free(st
->st_skeyid
.ptr
);
1160 prf
->set_key(prf
, *pss
);
1161 prf
->allocate_bytes(prf
, st
->st_ni
, NULL
);
1162 prf
->allocate_bytes(prf
, st
->st_nr
, &st
->st_skeyid
);
1169 skeyid_digisig(struct state
*st
)
1172 pseudo_random_function_t prf_alg
;
1175 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1176 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1179 loglog(RC_LOG_SERIOUS
, "%N not available to compute skeyid",
1180 pseudo_random_function_names
, prf_alg
);
1183 free(st
->st_skeyid
.ptr
);
1184 nir
= chunk_cat("cc", st
->st_ni
, st
->st_nr
);
1185 prf
->set_key(prf
, nir
);
1186 prf
->allocate_bytes(prf
, st
->st_shared
, &st
->st_skeyid
);
1192 /* Generate the SKEYID_* and new IV
1193 * See draft-ietf-ipsec-ike-01.txt 4.1
1195 static bool generate_skeyids_iv(struct state
*st
)
1197 /* Generate the SKEYID */
1198 switch (st
->st_oakley
.auth
)
1200 case OAKLEY_PRESHARED_KEY
:
1201 case XAUTHInitPreShared
:
1202 case XAUTHRespPreShared
:
1203 if (!skeyid_preshared(st
))
1209 case OAKLEY_RSA_SIG
:
1212 if (!skeyid_digisig(st
))
1218 case OAKLEY_DSS_SIG
:
1221 case OAKLEY_RSA_ENC
:
1222 case OAKLEY_RSA_ENC_REV
:
1223 case OAKLEY_ELGAMAL_ENC
:
1224 case OAKLEY_ELGAMAL_ENC_REV
:
1228 bad_case(st
->st_oakley
.auth
);
1231 /* generate SKEYID_* from SKEYID */
1233 char buf_skeyid_d
[] = { 0x00 };
1234 char buf_skeyid_a
[] = { 0x01 };
1235 char buf_skeyid_e
[] = { 0x02 };
1236 chunk_t seed_skeyid_d
= chunk_from_buf(buf_skeyid_d
);
1237 chunk_t seed_skeyid_a
= chunk_from_buf(buf_skeyid_a
);
1238 chunk_t seed_skeyid_e
= chunk_from_buf(buf_skeyid_e
);
1239 chunk_t icookie
= { st
->st_icookie
, COOKIE_SIZE
};
1240 chunk_t rcookie
= { st
->st_rcookie
, COOKIE_SIZE
};
1241 pseudo_random_function_t prf_alg
;
1244 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1245 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1246 prf
->set_key(prf
, st
->st_skeyid
);
1249 free(st
->st_skeyid_d
.ptr
);
1250 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1251 prf
->allocate_bytes(prf
, icookie
, NULL
);
1252 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1253 prf
->allocate_bytes(prf
, seed_skeyid_d
, &st
->st_skeyid_d
);
1256 free(st
->st_skeyid_a
.ptr
);
1257 prf
->allocate_bytes(prf
, st
->st_skeyid_d
, NULL
);
1258 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1259 prf
->allocate_bytes(prf
, icookie
, NULL
);
1260 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1261 prf
->allocate_bytes(prf
, seed_skeyid_a
, &st
->st_skeyid_a
);
1264 free(st
->st_skeyid_e
.ptr
);
1265 prf
->allocate_bytes(prf
, st
->st_skeyid_a
, NULL
);
1266 prf
->allocate_bytes(prf
, st
->st_shared
, NULL
);
1267 prf
->allocate_bytes(prf
, icookie
, NULL
);
1268 prf
->allocate_bytes(prf
, rcookie
, NULL
);
1269 prf
->allocate_bytes(prf
, seed_skeyid_e
, &st
->st_skeyid_e
);
1276 hash_algorithm_t hash_alg
;
1279 hash_alg
= oakley_to_hash_algorithm(st
->st_oakley
.hash
);
1280 hasher
= lib
->crypto
->create_hasher(lib
->crypto
, hash_alg
);
1281 st
->st_new_iv_len
= hasher
->get_hash_size(hasher
);
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
);
1289 hasher
->get_hash(hasher
, st
->st_gi
, NULL
);
1290 hasher
->get_hash(hasher
, st
->st_gr
, st
->st_new_iv
);
1291 hasher
->destroy(hasher
);
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 size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1302 /* free any existing key */
1303 free(st
->st_enc_key
.ptr
);
1305 if (keysize
> st
->st_skeyid_e
.len
)
1307 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1308 char seed_buf
[] = { 0x00 };
1309 chunk_t seed
= chunk_from_buf(seed_buf
);
1310 size_t prf_block_size
, i
;
1311 pseudo_random_function_t prf_alg
;
1314 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1315 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1316 prf
->set_key(prf
, st
->st_skeyid_e
);
1317 prf_block_size
= prf
->get_block_size(prf
);
1321 prf
->get_bytes(prf
, seed
, &keytemp
[i
]);
1322 i
+= prf_block_size
;
1327 seed
= chunk_create(&keytemp
[i
-prf_block_size
], prf_block_size
);
1330 st
->st_enc_key
= chunk_create(keytemp
, keysize
);
1334 st
->st_enc_key
= chunk_create(st
->st_skeyid_e
.ptr
, keysize
);
1336 st
->st_enc_key
= chunk_clone(st
->st_enc_key
);
1340 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1341 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1342 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1343 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1344 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1345 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1349 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1350 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1351 * New Group Mode, or ISAKMP Informational Exchanges).
1352 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1353 * If hashus argument is TRUE, we're generating a hash for our end.
1354 * See RFC2409 IKE 5.
1356 static size_t main_mode_hash(struct state
*st
, u_char
*hash_val
, bool hashi
,
1357 const pb_stream
*idpl
)
1359 chunk_t icookie
= { st
->st_icookie
, COOKIE_SIZE
};
1360 chunk_t rcookie
= { st
->st_rcookie
, COOKIE_SIZE
};
1361 chunk_t sa_body
= { st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
),
1362 st
->st_p1isa
.len
- sizeof(struct isakmp_generic
) };
1363 chunk_t id_body
= { idpl
->start
+ sizeof(struct isakmp_generic
),
1364 pbs_offset(idpl
) - sizeof(struct isakmp_generic
) };
1365 pseudo_random_function_t prf_alg
;
1367 size_t prf_block_size
;
1369 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1370 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1371 prf
->set_key(prf
, st
->st_skeyid
);
1375 prf
->get_bytes(prf
, st
->st_gi
, NULL
);
1376 prf
->get_bytes(prf
, st
->st_gr
, NULL
);
1377 prf
->get_bytes(prf
, icookie
, NULL
);
1378 prf
->get_bytes(prf
, rcookie
, NULL
);
1382 prf
->get_bytes(prf
, st
->st_gr
, NULL
);
1383 prf
->get_bytes(prf
, st
->st_gi
, NULL
);
1384 prf
->get_bytes(prf
, rcookie
, NULL
);
1385 prf
->get_bytes(prf
, icookie
, NULL
);
1389 DBG_log("hashing %u bytes of SA", sa_body
.len
)
1391 prf
->get_bytes(prf
, sa_body
, NULL
);
1393 /* Hash identification payload, without generic payload header.
1394 * We used to reconstruct ID Payload for this purpose, but now
1395 * we use the bytes as they appear on the wire to avoid
1396 * "spelling problems".
1398 prf
->get_bytes(prf
, id_body
, hash_val
);
1399 prf_block_size
= prf
->get_block_size(prf
);
1402 return prf_block_size
;
1405 /* Create an RSA signature of a hash.
1406 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1407 * Use PKCS#1 version 1.5 encryption of hash (called
1408 * RSAES-PKCS1-V1_5) in PKCS#2.
1410 static size_t RSA_sign_hash(struct connection
*c
, u_char sig_val
[RSA_MAX_OCTETS
],
1411 const u_char
*hash_val
, size_t hash_len
)
1414 smartcard_t
*sc
= c
->spd
.this.sc
;
1416 if (sc
== NULL
) /* no smartcard */
1418 const struct RSA_private_key
*k
= get_RSA_private_key(c
);
1421 return 0; /* failure: no key to use */
1424 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1425 sign_hash(k
, hash_val
, hash_len
, sig_val
, sz
);
1427 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1429 lock_certs_and_keys("RSA_sign_hash");
1430 if (!scx_establish_context(sc
) || !scx_login(sc
))
1432 scx_release_context(sc
);
1433 unlock_certs_and_keys("RSA_sign_hash");
1437 sz
= scx_get_keylength(sc
);
1440 plog("failed to get keylength from smartcard");
1441 scx_release_context(sc
);
1442 unlock_certs_and_keys("RSA_sign_hash");
1446 DBG(DBG_CONTROL
| DBG_CRYPT
,
1447 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1448 , (int)sc
->slot
, sc
->id
)
1450 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1451 if (!pkcs11_keep_state
)
1452 scx_release_context(sc
);
1453 unlock_certs_and_keys("RSA_sign_hash");
1458 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1460 * As a side effect, on success, the public key is copied into the
1461 * state object to record the authenticator.
1463 * Can fail because wrong public key is used or because hash disagrees.
1464 * We distinguish because diagnostics should also.
1466 * The result is NULL if the Signature checked out.
1467 * Otherwise, the first character of the result indicates
1468 * how far along failure occurred. A greater character signifies
1472 * 0 reserved for caller
1473 * 1 SIG length doesn't match key length -- wrong key
1474 * 2-8 malformed ECB after decryption -- probably wrong key
1475 * 9 decrypted hash != computed hash -- probably correct key
1477 * Although the math should be the same for generating and checking signatures,
1478 * it is not: the knowledge of the private key allows more efficient (i.e.
1479 * different) computation for encryption.
1481 static err_t
try_RSA_signature(const u_char hash_val
[MAX_DIGEST_LEN
],
1482 size_t hash_len
, const pb_stream
*sig_pbs
,
1483 pubkey_t
*kr
, struct state
*st
)
1485 const u_char
*sig_val
= sig_pbs
->cur
;
1486 size_t sig_len
= pbs_left(sig_pbs
);
1487 u_char s
[RSA_MAX_OCTETS
]; /* for decrypted sig_val */
1488 u_char
*hash_in_s
= &s
[sig_len
- hash_len
];
1489 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1491 /* decrypt the signature -- reversing RSA_sign_hash */
1492 if (sig_len
!= k
->k
)
1494 /* XXX notification: INVALID_KEY_INFORMATION */
1495 return "1" "SIG length does not match public key length";
1498 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1503 n_to_mpz(c
, sig_val
, sig_len
);
1504 mpz_powm(c
, c
, &k
->e
, &k
->n
);
1506 temp_s
= mpz_to_n(c
, sig_len
); /* back to octets */
1507 memcpy(s
, temp_s
.ptr
, sig_len
);
1512 /* sanity check on signature: see if it matches
1513 * PKCS#1 v1.5 8.1 encryption-block formatting
1519 ugh
= "2" "no leading 00";
1520 else if (hash_in_s
[-1] != 0x00)
1521 ugh
= "3" "00 separator not present";
1522 else if (s
[1] == 0x01)
1526 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1530 ugh
= "4" "invalid Padding String";
1535 else if (s
[1] == 0x02)
1539 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1543 ugh
= "5" "invalid Padding String";
1549 ugh
= "6" "Block Type not 01 or 02";
1553 /* note: it might be a good idea to make sure that
1554 * an observer cannot tell what kind of failure happened.
1555 * I don't know what this means in practice.
1557 /* We probably selected the wrong public key for peer:
1558 * SIG Payload decrypted into malformed ECB
1560 /* XXX notification: INVALID_KEY_INFORMATION */
1565 /* We have the decoded hash: see if it matches. */
1566 if (memcmp(hash_val
, hash_in_s
, hash_len
) != 0)
1568 /* good: header, hash, signature, and other payloads well-formed
1569 * good: we could find an RSA Sig key for the peer.
1570 * bad: hash doesn't match
1571 * Guess: sides disagree about key to be used.
1573 DBG_cond_dump(DBG_CRYPT
, "decrypted SIG", s
, sig_len
);
1574 DBG_cond_dump(DBG_CRYPT
, "computed HASH", hash_val
, hash_len
);
1575 /* XXX notification: INVALID_HASH_INFORMATION */
1576 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1579 /* Success: copy successful key into state.
1580 * There might be an old one if we previously aborted this
1583 unreference_key(&st
->st_peer_pubkey
);
1584 st
->st_peer_pubkey
= reference_key(kr
);
1586 return NULL
; /* happy happy */
1589 /* Check signature against all RSA public keys we can find.
1590 * If we need keys from DNS KEY records, and they haven't been fetched,
1591 * return STF_SUSPEND to ask for asynch DNS lookup.
1593 * Note: parameter keys_from_dns contains results of DNS lookup for key
1594 * or is NULL indicating lookup not yet tried.
1596 * take_a_crack is a helper function. Mostly forensic.
1597 * If only we had coroutines.
1600 /* RSA_check_signature's args that take_a_crack needs */
1602 const u_char
*hash_val
;
1604 const pb_stream
*sig_pbs
;
1606 /* state carried between calls */
1607 err_t best_ugh
; /* most successful failure */
1608 int tried_cnt
; /* number of keys tried */
1609 char tried
[50]; /* keyids of tried public keys */
1610 char *tn
; /* roof of tried[] */
1613 static bool take_a_crack(struct tac_state
*s
, pubkey_t
*kr
,
1614 const char *story USED_BY_DEBUG
)
1616 err_t ugh
= try_RSA_signature(s
->hash_val
, s
->hash_len
, s
->sig_pbs
1618 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1623 DBG(DBG_CRYPT
| DBG_CONTROL
1624 , DBG_log("an RSA Sig check passed with *%s [%s]"
1625 , k
->keyid
, story
));
1631 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1632 , ugh
+ 1, k
->keyid
, story
));
1633 if (s
->best_ugh
== NULL
|| s
->best_ugh
[0] < ugh
[0])
1636 && s
->tn
- s
->tried
+ KEYID_BUF
+ 2 < (ptrdiff_t)sizeof(s
->tried
))
1638 strcpy(s
->tn
, " *");
1639 strcpy(s
->tn
+ 2, k
->keyid
);
1640 s
->tn
+= strlen(s
->tn
);
1646 static stf_status
RSA_check_signature(const struct id
* peer
, struct state
*st
,
1647 const u_char hash_val
[MAX_DIGEST_LEN
],
1648 size_t hash_len
, const pb_stream
*sig_pbs
,
1650 const pubkey_list_t
*keys_from_dns
,
1651 #endif /* USE_KEYRR */
1652 const struct gw_info
*gateways_from_dns
)
1654 const struct connection
*c
= st
->st_connection
;
1656 err_t dns_ugh
= NULL
;
1659 s
.hash_val
= hash_val
;
1660 s
.hash_len
= hash_len
;
1661 s
.sig_pbs
= sig_pbs
;
1667 /* try all gateway records hung off c */
1668 if (c
->policy
& POLICY_OPPO
)
1672 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1674 /* only consider entries that have a key and are for our peer */
1675 if (gw
->gw_key_present
1676 && same_id(&gw
->gw_id
, &c
->spd
.that
.id
)
1677 && take_a_crack(&s
, gw
->key
, "key saved from DNS TXT"))
1682 /* try all appropriate Public keys */
1684 pubkey_list_t
*p
, **pp
;
1688 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1690 pubkey_t
*key
= p
->key
;
1692 if (key
->alg
== PUBKEY_ALG_RSA
&& same_id(peer
, &key
->id
))
1694 time_t now
= time(NULL
);
1696 /* check if found public key has expired */
1697 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1699 loglog(RC_LOG_SERIOUS
,
1700 "cached RSA public key has expired and has been deleted");
1701 *pp
= free_public_keyentry(p
);
1702 continue; /* continue with next public key */
1705 if (take_a_crack(&s
, key
, "preloaded key"))
1712 /* if no key was found (evidenced by best_ugh == NULL)
1713 * and that side of connection is key_from_DNS_on_demand
1714 * then go search DNS for keys for peer.
1716 if (s
.best_ugh
== NULL
&& c
->spd
.that
.key_from_DNS_on_demand
)
1718 if (gateways_from_dns
!= NULL
)
1721 const struct gw_info
*gwp
;
1723 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1724 if (gwp
->gw_key_present
1725 && take_a_crack(&s
, gwp
->key
, "key from DNS TXT"))
1729 else if (keys_from_dns
!= NULL
)
1732 const pubkey_list_t
*kr
;
1734 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1735 if (kr
->key
->alg
== PUBKEY_ALG_RSA
1736 && take_a_crack(&s
, kr
->key
, "key from DNS KEY"))
1739 #endif /* USE_KEYRR */
1742 /* nothing yet: ask for asynch DNS lookup */
1747 /* no acceptable key was found: diagnose */
1749 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1751 (void) idtoa(peer
, id_buf
, sizeof(id_buf
));
1753 if (s
.best_ugh
== NULL
)
1755 if (dns_ugh
== NULL
)
1756 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1759 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1760 "; DNS search for KEY failed (%s)"
1763 /* ??? is this the best code there is? */
1764 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1767 if (s
.best_ugh
[0] == '9')
1769 loglog(RC_LOG_SERIOUS
, "%s", s
.best_ugh
+ 1);
1770 /* XXX Could send notification back */
1771 return STF_FAIL
+ INVALID_HASH_INFORMATION
;
1775 if (s
.tried_cnt
== 1)
1777 loglog(RC_LOG_SERIOUS
1778 , "Signature check (on %s) failed (wrong key?); tried%s"
1781 DBG_log("public key for %s failed:"
1782 " decrypted SIG payload into a malformed ECB (%s)"
1783 , id_buf
, s
.best_ugh
+ 1));
1787 loglog(RC_LOG_SERIOUS
1788 , "Signature check (on %s) failed:"
1789 " tried%s keys but none worked."
1792 DBG_log("all %d public keys for %s failed:"
1793 " best decrypted SIG payload into a malformed ECB (%s)"
1794 , s
.tried_cnt
, id_buf
, s
.best_ugh
+ 1));
1796 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1801 static notification_t
accept_nonce(struct msg_digest
*md
, chunk_t
*dest
,
1804 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1805 size_t len
= pbs_left(nonce_pbs
);
1807 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1809 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1810 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1811 return PAYLOAD_MALFORMED
; /* ??? */
1814 *dest
= chunk_create(nonce_pbs
->cur
, len
);
1815 *dest
= chunk_clone(*dest
);
1816 return NOTHING_WRONG
;
1819 /* encrypt message, sans fixed part of header
1820 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1821 * The theory is that there will be no "backing out", so we commit to IV.
1822 * We also close the pbs.
1825 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1827 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1828 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1831 size_t crypter_block_size
;
1832 encryption_algorithm_t enc_alg
;
1835 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1836 enc_alg
= oakley_to_encryption_algorithm(st
->st_oakley
.encrypt
);
1837 crypter
= lib
->crypto
->create_crypter(lib
->crypto
, enc_alg
, st
->st_enc_key
.len
);
1838 crypter_block_size
= crypter
->get_block_size(crypter
);
1840 /* Pad up to multiple of encryption blocksize.
1841 * See the description associated with the definition of
1842 * struct isakmp_hdr in packet.h.
1845 size_t padding
= pad_up(enc_len
, crypter_block_size
);
1849 if (!out_zero(padding
, pbs
, "encryption padding"))
1855 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1856 data
= chunk_create(enc_start
, enc_len
);
1858 /* form iv by truncation */
1859 st
->st_new_iv_len
= crypter_block_size
;
1860 iv
= chunk_create(st
->st_new_iv
, st
->st_new_iv_len
);
1862 crypter
->set_key(crypter
, st
->st_enc_key
);
1863 crypter
->encrypt(crypter
, data
, iv
, NULL
);
1864 crypter
->destroy(crypter
);
1866 new_iv
= data
.ptr
+ data
.len
- crypter_block_size
;
1867 memcpy(st
->st_new_iv
, new_iv
, crypter_block_size
);
1869 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1874 /* Compute HASH(1), HASH(2) of Quick Mode.
1875 * HASH(1) is part of Quick I1 message.
1876 * HASH(2) is part of Quick R1 message.
1877 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1878 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1880 static size_t quick_mode_hash12(u_char
*dest
, u_char
*start
, u_char
*roof
,
1881 const struct state
*st
, const msgid_t
*msgid
,
1884 chunk_t msgid_chunk
= chunk_from_thing(*msgid
);
1885 chunk_t msg_chunk
= { start
, roof
- start
};
1886 pseudo_random_function_t prf_alg
;
1888 size_t prf_block_size
;
1890 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1891 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1892 prf
->set_key(prf
, st
->st_skeyid_a
);
1893 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
1896 prf
->get_bytes(prf
, st
->st_ni
, NULL
); /* include Ni_b in the hash */
1898 prf
->get_bytes(prf
, msg_chunk
, dest
);
1899 prf_block_size
= prf
->get_block_size(prf
);
1903 DBG_log("HASH(%d) computed:", hash2
+ 1);
1904 DBG_dump("", dest
, prf_block_size
)
1906 return prf_block_size
;
1909 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1910 * Used by: quick_inR1_outI2, quick_inI2
1911 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1912 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1913 * Message ID and Nonces. This is a mistake.
1915 static size_t quick_mode_hash3(u_char
*dest
, struct state
*st
)
1917 char seed_buf
[] = { 0x00 };
1918 chunk_t seed_chunk
= chunk_from_buf(seed_buf
);
1919 chunk_t msgid_chunk
= chunk_from_thing(st
->st_msgid
);
1920 pseudo_random_function_t prf_alg
;
1922 size_t prf_block_size
;
1924 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
1925 prf
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
1926 prf
->set_key(prf
, st
->st_skeyid_a
);
1927 prf
->get_bytes(prf
, seed_chunk
, NULL
);
1928 prf
->get_bytes(prf
, msgid_chunk
, NULL
);
1929 prf
->get_bytes(prf
, st
->st_ni
, NULL
);
1930 prf
->get_bytes(prf
, st
->st_nr
, dest
);
1931 prf_block_size
= prf
->get_block_size(prf
);
1934 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, prf_block_size
);
1935 return prf_block_size
;
1938 /* Compute Phase 2 IV.
1939 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1941 void init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1943 chunk_t iv_chunk
= { st
->st_ph1_iv
, st
->st_ph1_iv_len
};
1944 chunk_t msgid_chunk
= chunk_from_thing(*msgid
);
1945 hash_algorithm_t hash_alg
;
1948 hash_alg
= oakley_to_hash_algorithm(st
->st_oakley
.hash
);
1949 hasher
= lib
->crypto
->create_hasher(lib
->crypto
, hash_alg
);
1951 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:",
1952 st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1954 st
->st_new_iv_len
= hasher
->get_hash_size(hasher
);
1955 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1957 hasher
->get_hash(hasher
, iv_chunk
, NULL
);
1958 hasher
->get_hash(hasher
, msgid_chunk
, st
->st_new_iv
);
1959 hasher
->destroy(hasher
);
1961 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:",
1962 st
->st_new_iv
, st
->st_new_iv_len
);
1965 /* Initiate quick mode.
1966 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1967 * (see RFC 2409 "IKE" 5.5)
1968 * Note: this is not called from demux.c
1971 static bool emit_subnet_id(ip_subnet
*net
, u_int8_t np
, u_int8_t protoid
,
1972 u_int16_t port
, pb_stream
*outs
)
1974 struct isakmp_ipsec_id id
;
1977 const unsigned char *tbp
;
1981 id
.isaiid_idtype
= subnetishost(net
)
1982 ?
aftoinfo(subnettypeof(net
))->id_addr
1983 : aftoinfo(subnettypeof(net
))->id_subnet
;
1984 id
.isaiid_protoid
= protoid
;
1985 id
.isaiid_port
= port
;
1987 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
1990 networkof(net
, &ta
);
1991 tal
= addrbytesptr(&ta
, &tbp
);
1992 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
1995 if (!subnetishost(net
))
1998 tal
= addrbytesptr(&ta
, &tbp
);
1999 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
2003 close_output_pbs(&id_pbs
);
2007 stf_status
quick_outI1(int whack_sock
, struct state
*isakmp_sa
,
2008 struct connection
*c
, lset_t policy
, unsigned long try,
2009 so_serial_t replacing
)
2011 struct state
*st
= duplicate_state(isakmp_sa
);
2012 pb_stream reply
; /* not really a reply */
2014 u_char
/* set by START_HASH_PAYLOAD: */
2015 *r_hashval
, /* where in reply to jam hash value */
2016 *r_hash_start
; /* start of what is to be hashed */
2017 bool has_client
= c
->spd
.this.has_client
|| c
->spd
.that
.has_client
||
2018 c
->spd
.this.protocol
|| c
->spd
.that
.protocol
||
2019 c
->spd
.this.port
|| c
->spd
.that
.port
;
2021 bool send_natoa
= FALSE
;
2022 u_int8_t np
= ISAKMP_NEXT_NONE
;
2024 st
->st_whack_sock
= whack_sock
;
2025 st
->st_connection
= c
;
2026 set_cur_state(st
); /* we must reset before exit */
2027 st
->st_policy
= policy
;
2030 st
->st_myuserprotoid
= c
->spd
.this.protocol
;
2031 st
->st_peeruserprotoid
= c
->spd
.that
.protocol
;
2032 st
->st_myuserport
= c
->spd
.this.port
;
2033 st
->st_peeruserport
= c
->spd
.that
.port
;
2035 st
->st_msgid
= generate_msgid(isakmp_sa
);
2036 st
->st_state
= STATE_QUICK_I1
;
2038 insert_state(st
); /* needs cookies, connection, and msgid */
2040 if (replacing
== SOS_NOBODY
)
2041 plog("initiating Quick Mode %s {using isakmp#%lu}"
2042 , prettypolicy(policy
)
2043 , isakmp_sa
->st_serialno
);
2045 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2046 , prettypolicy(policy
)
2048 , isakmp_sa
->st_serialno
);
2050 if (isakmp_sa
->nat_traversal
& NAT_T_DETECTED
)
2052 /* Duplicate nat_traversal status in new state */
2053 st
->nat_traversal
= isakmp_sa
->nat_traversal
;
2055 if (isakmp_sa
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
))
2058 nat_traversal_change_port_lookup(NULL
, st
);
2061 st
->nat_traversal
= 0;
2063 /* are we going to send a NAT-OA payload? */
2064 if ((st
->nat_traversal
& NAT_T_WITH_NATOA
)
2065 && !(st
->st_policy
& POLICY_TUNNEL
)
2066 && (st
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
)))
2069 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
2070 ISAKMP_NEXT_NATOA_RFC
: ISAKMP_NEXT_NATOA_DRAFTS
;
2074 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
2078 struct isakmp_hdr hdr
;
2080 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
2081 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
2082 hdr
.isa_xchg
= ISAKMP_XCHG_QUICK
;
2083 hdr
.isa_msgid
= st
->st_msgid
;
2084 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
2085 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
2086 memcpy(hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
2087 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
2090 return STF_INTERNAL_ERROR
;
2094 /* HASH(1) -- create and note space to be filled later */
2095 START_HASH_PAYLOAD(rbody
, ISAKMP_NEXT_SA
);
2100 * See if pfs_group has been specified for this conn,
2101 * if not, fallback to old use-same-as-P1 behaviour
2104 if (st
->st_connection
)
2105 st
->st_pfs_group
= ike_alg_pfsgroup(st
->st_connection
, policy
);
2106 if (!st
->st_pfs_group
)
2108 /* If PFS specified, use the same group as during Phase 1:
2109 * since no negotiation is possible, we pick one that is
2110 * very likely supported.
2112 st
->st_pfs_group
= policy
& POLICY_PFS? isakmp_sa
->st_oakley
.group
: NULL
;
2114 /* Emit SA payload based on a subset of the policy bits.
2115 * POLICY_COMPRESS is considered iff we can do IPcomp.
2118 lset_t pm
= POLICY_ENCRYPT
| POLICY_AUTHENTICATE
;
2121 pm
|= POLICY_COMPRESS
;
2124 , &ipsec_sadb
[(st
->st_policy
& pm
) >> POLICY_IPSEC_SHIFT
]
2125 , st
, FALSE
, ISAKMP_NEXT_NONCE
))
2128 return STF_INTERNAL_ERROR
;
2133 if (!build_and_ship_nonce(&st
->st_ni
, &rbody
2134 , policy
& POLICY_PFS? ISAKMP_NEXT_KE
: has_client? ISAKMP_NEXT_ID
: np
2138 return STF_INTERNAL_ERROR
;
2141 /* [ KE ] out (for PFS) */
2143 if (st
->st_pfs_group
!= NULL
)
2145 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_pfs_group
2146 , &rbody
, has_client? ISAKMP_NEXT_ID
: np
))
2149 return STF_INTERNAL_ERROR
;
2153 /* [ IDci, IDcr ] out */
2156 /* IDci (we are initiator), then IDcr (peer is responder) */
2157 if (!emit_subnet_id(&c
->spd
.this.client
2158 , ISAKMP_NEXT_ID
, st
->st_myuserprotoid
, st
->st_myuserport
, &rbody
)
2159 || !emit_subnet_id(&c
->spd
.that
.client
2160 , np
, st
->st_peeruserprotoid
, st
->st_peeruserport
, &rbody
))
2163 return STF_INTERNAL_ERROR
;
2167 /* Send NAT-OA if our address is NATed */
2170 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE
, &rbody
, st
))
2173 return STF_INTERNAL_ERROR
;
2177 /* finish computing HASH(1), inserting it in output */
2178 (void) quick_mode_hash12(r_hashval
, r_hash_start
, rbody
.cur
2179 , st
, &st
->st_msgid
, FALSE
);
2181 /* encrypt message, except for fixed part of header */
2183 init_phase2_iv(isakmp_sa
, &st
->st_msgid
);
2184 st
->st_new_iv_len
= isakmp_sa
->st_new_iv_len
;
2185 memcpy(st
->st_new_iv
, isakmp_sa
->st_new_iv
, st
->st_new_iv_len
);
2187 if (!encrypt_message(&rbody
, st
))
2190 return STF_INTERNAL_ERROR
;
2193 /* save packet, now that we know its size */
2194 st
->st_tpacket
= chunk_create(reply
.start
, pbs_offset(&reply
));
2195 st
->st_tpacket
= chunk_clone(st
->st_tpacket
);
2197 /* send the packet */
2199 send_packet(st
, "quick_outI1");
2202 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
2204 if (replacing
== SOS_NOBODY
)
2205 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2207 , enum_name(&state_names
, st
->st_state
));
2209 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2210 , "%s: initiate to replace #%lu"
2211 , enum_name(&state_names
, st
->st_state
)
2219 * Decode the CERT payload of Phase 1.
2221 static void decode_cert(struct msg_digest
*md
)
2223 struct payload_digest
*p
;
2225 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2227 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2230 blob
.ptr
= p
->pbs
.cur
;
2231 blob
.len
= pbs_left(&p
->pbs
);
2232 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2234 x509cert_t cert
= empty_x509cert
;
2235 if (parse_x509cert(blob
, 0, &cert
))
2237 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2240 DBG_log("Public key validated")
2242 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2246 plog("X.509 certificate rejected");
2248 free_generalNames(cert
.subjectAltName
, FALSE
);
2249 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2252 plog("Syntax error in X.509 certificate");
2254 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2256 x509cert_t
*cert
= NULL
;
2258 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2259 store_x509certs(&cert
, strict_crl_policy
);
2261 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2265 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2266 enum_show(&cert_type_names
, cert
->isacert_type
));
2267 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2273 * Decode the CR payload of Phase 1.
2275 static void decode_cr(struct msg_digest
*md
, struct connection
*c
)
2277 struct payload_digest
*p
;
2279 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2281 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2284 ca_name
.len
= pbs_left(&p
->pbs
);
2285 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2287 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2289 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2293 if (ca_name
.len
> 0)
2297 if (!is_asn1(ca_name
))
2300 gn
= malloc_thing(generalName_t
);
2301 ca_name
= chunk_clone(ca_name
);
2302 gn
->kind
= GN_DIRECTORY_NAME
;
2304 gn
->next
= c
->requested_ca
;
2305 c
->requested_ca
= gn
;
2307 c
->got_certrequest
= TRUE
;
2309 DBG(DBG_PARSING
| DBG_CONTROL
,
2310 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2311 DBG_log("requested CA: '%s'", buf
);
2315 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2316 enum_show(&cert_type_names
, cr
->isacr_type
));
2320 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2321 * Note: we may change connections as a result.
2322 * We must be called before SIG or HASH are decoded since we
2323 * may change the peer's RSA key or ID.
2325 static bool decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2327 struct state
*const st
= md
->st
;
2328 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2329 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2330 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2332 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2333 * It talks about the protocol ID and Port fields of the ID
2334 * Payload, but they don't exist as such in Phase 1.
2335 * We use more appropriate names.
2336 * isaid_doi_specific_a is in place of Protocol ID.
2337 * isaid_doi_specific_b is in place of Port.
2338 * Besides, there is no good reason for allowing these to be
2339 * other than 0 in Phase 1.
2341 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2342 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2343 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2345 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2346 "accepted with port_floating NAT-T",
2347 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2349 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2350 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2352 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2354 , IPPROTO_UDP
, IKE_UDP_PORT
2355 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2359 peer
->kind
= id
->isaid_idtype
;
2365 /* failure mode for initaddr is probably inappropriate address length */
2367 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2368 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2373 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2374 , enum_show(&ident_names
, peer
->kind
), ugh
);
2375 /* XXX Could send notification back */
2382 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2384 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2389 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2391 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2392 , enum_show(&ident_names
, peer
->kind
));
2396 /* ??? ought to do some more sanity check, but what? */
2398 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2402 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2404 DBG_dump_chunk("KEY ID:", peer
->name
));
2407 case ID_DER_ASN1_DN
:
2408 peer
->name
= chunk_create(id_pbs
->cur
, pbs_left(id_pbs
));
2410 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2414 /* XXX Could send notification back */
2415 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2416 , enum_show(&ident_names
, peer
->kind
));
2423 idtoa(peer
, buf
, sizeof(buf
));
2424 plog("Peer ID is %s: '%s'",
2425 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2428 /* check for certificates */
2433 /* Now that we've decoded the ID payload, let's see if we
2434 * need to switch connections.
2435 * We must not switch horses if we initiated:
2436 * - if the initiation was explicit, we'd be ignoring user's intent
2437 * - if opportunistic, we'll lose our HOLD info
2439 static bool switch_connection(struct msg_digest
*md
, struct id
*peer
,
2442 struct state
*const st
= md
->st
;
2443 struct connection
*c
= st
->st_connection
;
2445 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2446 ? st
->st_peer_pubkey
->issuer
: chunk_empty
;
2451 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2452 DBG_log("peer CA: '%s'", buf
);
2459 if (!same_id(&c
->spd
.that
.id
, peer
))
2461 char expect
[BUF_LEN
]
2464 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2465 idtoa(peer
, found
, sizeof(found
));
2466 loglog(RC_LOG_SERIOUS
2467 , "we require peer to have ID '%s', but peer declares '%s'"
2475 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.that
.ca
, "%none");
2476 DBG_log("required CA: '%s'", buf
);
2479 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2481 loglog(RC_LOG_SERIOUS
2482 , "we don't accept the peer's CA");
2488 struct connection
*r
;
2490 /* check for certificate requests */
2493 r
= refine_host_connection(st
, peer
, peer_ca
);
2495 /* delete the collected certificate requests */
2496 free_generalNames(c
->requested_ca
, TRUE
);
2497 c
->requested_ca
= NULL
;
2503 idtoa(peer
, buf
, sizeof(buf
));
2504 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2511 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2512 DBG_log("offered CA: '%s'", buf
);
2517 /* apparently, r is an improvement on c -- replace */
2520 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2521 if (r
->kind
== CK_TEMPLATE
)
2523 /* instantiate it, filling in peer's ID */
2524 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2525 , c
->spd
.that
.host_port
, NULL
, peer
);
2528 /* copy certificate request info */
2529 r
->got_certrequest
= c
->got_certrequest
;
2531 st
->st_connection
= r
; /* kill reference to c */
2532 set_cur_connection(r
);
2533 connection_discard(c
);
2535 else if (c
->spd
.that
.has_id_wildcards
)
2537 free_id_content(&c
->spd
.that
.id
);
2538 c
->spd
.that
.id
= *peer
;
2539 c
->spd
.that
.has_id_wildcards
= FALSE
;
2540 unshare_id_content(&c
->spd
.that
.id
);
2546 /* Decode the variable part of an ID packet (during Quick Mode).
2547 * This is designed for packets that identify clients, not peers.
2548 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2549 * (1) it is wrong and (2) we use this value for inband signalling.
2551 static bool decode_net_id(struct isakmp_ipsec_id
*id
, pb_stream
*id_pbs
,
2552 ip_subnet
*net
, const char *which
)
2554 const struct af_info
*afi
= NULL
;
2556 /* Note: the following may be a pointer into static memory
2557 * that may be recycled, but only if the type is not known.
2558 * That case is disposed of very early -- in the first switch.
2560 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2562 switch (id
->isaiid_idtype
)
2565 case ID_IPV4_ADDR_SUBNET
:
2566 case ID_IPV4_ADDR_RANGE
:
2567 afi
= &af_inet4_info
;
2570 case ID_IPV6_ADDR_SUBNET
:
2571 case ID_IPV6_ADDR_RANGE
:
2572 afi
= &af_inet6_info
;
2577 /* XXX support more */
2578 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2580 /* XXX Could send notification back */
2584 switch (id
->isaiid_idtype
)
2589 ip_address temp_address
;
2592 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2596 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2597 , which
, idtypename
, ugh
);
2598 /* XXX Could send notification back */
2601 if (isanyaddr(&temp_address
))
2603 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2604 , which
, idtypename
, ip_str(&temp_address
));
2605 /* XXX Could send notification back */
2608 happy(addrtosubnet(&temp_address
, net
));
2609 DBG(DBG_PARSING
| DBG_CONTROL
2610 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2614 case ID_IPV4_ADDR_SUBNET
:
2615 case ID_IPV6_ADDR_SUBNET
:
2617 ip_address temp_address
, temp_mask
;
2620 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2622 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2623 , which
, idtypename
);
2624 /* XXX Could send notification back */
2627 ugh
= initaddr(id_pbs
->cur
2628 , afi
->ia_sz
, afi
->af
, &temp_address
);
2630 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2631 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2633 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2635 if (ugh
== NULL
&& subnetisnone(net
))
2636 ugh
= "contains only anyaddr";
2639 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2640 , which
, idtypename
, ugh
);
2641 /* XXX Could send notification back */
2644 DBG(DBG_PARSING
| DBG_CONTROL
,
2646 char temp_buff
[SUBNETTOT_BUF
];
2648 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2649 DBG_log("%s is subnet %s", which
, temp_buff
);
2654 case ID_IPV4_ADDR_RANGE
:
2655 case ID_IPV6_ADDR_RANGE
:
2657 ip_address temp_address_from
, temp_address_to
;
2660 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2662 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2663 , which
, idtypename
);
2664 /* XXX Could send notification back */
2667 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2669 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2670 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2673 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2674 , which
, idtypename
, ugh
);
2675 /* XXX Could send notification back */
2679 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2680 if (ugh
== NULL
&& subnetisnone(net
))
2681 ugh
= "contains only anyaddr";
2684 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2686 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2687 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2688 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2689 " %s - %s unacceptable: %s"
2690 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2693 DBG(DBG_PARSING
| DBG_CONTROL
,
2695 char temp_buff
[SUBNETTOT_BUF
];
2697 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2698 DBG_log("%s is subnet %s (received as range)"
2699 , which
, temp_buff
);
2705 /* set the port selector */
2706 setportof(htons(id
->isaiid_port
), &net
->addr
);
2708 DBG(DBG_PARSING
| DBG_CONTROL
,
2709 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2715 /* like decode, but checks that what is received matches what was sent */
2716 static bool check_net_id(struct isakmp_ipsec_id
*id
, pb_stream
*id_pbs
,
2717 u_int8_t
*protoid
, u_int16_t
*port
, ip_subnet
*net
,
2722 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2725 if (!samesubnet(net
, &net_temp
)
2726 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2728 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2735 * look for the existence of a non-expiring preloaded public key
2737 static bool has_preloaded_public_key(struct state
*st
)
2739 struct connection
*c
= st
->st_connection
;
2741 /* do not consider rw connections since
2742 * the peer's identity must be known
2744 if (c
->kind
== CK_PERMANENT
)
2748 /* look for a matching RSA public key */
2749 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2751 pubkey_t
*key
= p
->key
;
2753 if (key
->alg
== PUBKEY_ALG_RSA
&&
2754 same_id(&c
->spd
.that
.id
, &key
->id
) &&
2755 key
->until_time
== UNDEFINED_TIME
)
2757 /* found a preloaded public key */
2766 * Produce the new key material of Quick Mode.
2767 * RFC 2409 "IKE" section 5.5
2768 * specifies how this is to be done.
2770 static void compute_proto_keymat(struct state
*st
, u_int8_t protoid
,
2771 struct ipsec_proto_info
*pi
)
2773 size_t needed_len
= 0; /* bytes of keying material needed */
2775 /* Add up the requirements for keying material
2776 * (It probably doesn't matter if we produce too much!)
2780 case PROTO_IPSEC_ESP
:
2781 switch (pi
->attrs
.transid
)
2787 needed_len
= DES_CBC_BLOCK_SIZE
;
2790 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2793 #ifndef NO_KERNEL_ALG
2794 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2795 /* XXX: check key_len "coupling with kernel.c's */
2796 if (pi
->attrs
.key_len
) {
2797 needed_len
=pi
->attrs
.key_len
/8;
2798 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2799 "key_len=%d from peer",
2805 bad_case(pi
->attrs
.transid
);
2808 #ifndef NO_KERNEL_ALG
2809 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2810 "needed_len (after ESP enc)=%d",
2812 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2813 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2816 switch (pi
->attrs
.auth
)
2818 case AUTH_ALGORITHM_NONE
:
2820 case AUTH_ALGORITHM_HMAC_MD5
:
2821 needed_len
+= HMAC_MD5_KEY_LEN
;
2823 case AUTH_ALGORITHM_HMAC_SHA1
:
2824 needed_len
+= HMAC_SHA1_KEY_LEN
;
2826 case AUTH_ALGORITHM_DES_MAC
:
2828 bad_case(pi
->attrs
.auth
);
2830 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2831 "needed_len (after ESP auth)=%d",
2835 case PROTO_IPSEC_AH
:
2836 switch (pi
->attrs
.transid
)
2839 needed_len
= HMAC_MD5_KEY_LEN
;
2842 needed_len
= HMAC_SHA1_KEY_LEN
;
2845 bad_case(pi
->attrs
.transid
);
2853 pi
->keymat_len
= needed_len
;
2855 /* Allocate space for the keying material. Although only needed_len bytes
2856 * are desired, we must round up to a multiple of hash_size
2857 * so that our buffer isn't overrun.
2860 size_t needed_space
; /* space needed for keying material (rounded up) */
2861 size_t i
, prf_block_size
;
2862 chunk_t protoid_chunk
= chunk_from_thing(protoid
);
2863 chunk_t spi_our
= chunk_from_thing(pi
->our_spi
);
2864 chunk_t spi_peer
= chunk_from_thing(pi
->attrs
.spi
);
2865 pseudo_random_function_t prf_alg
;
2866 prf_t
*prf_our
, *prf_peer
;
2868 prf_alg
= oakley_to_prf(st
->st_oakley
.hash
);
2869 prf_our
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
2870 prf_peer
= lib
->crypto
->create_prf(lib
->crypto
, prf_alg
);
2871 prf_our
->set_key(prf_our
, st
->st_skeyid_d
);
2872 prf_peer
->set_key(prf_peer
, st
->st_skeyid_d
);
2873 prf_block_size
= prf_our
->get_block_size(prf_our
);
2875 needed_space
= needed_len
+ pad_up(needed_len
, prf_block_size
);
2876 replace(pi
->our_keymat
, malloc(needed_space
));
2877 replace(pi
->peer_keymat
, malloc(needed_space
));
2881 char *keymat_i_our
= pi
->our_keymat
+ i
;
2882 char *keymat_i_peer
= pi
->peer_keymat
+ i
;
2883 chunk_t keymat_our
= { keymat_i_our
, prf_block_size
};
2884 chunk_t keymat_peer
= { keymat_i_peer
, prf_block_size
};
2886 if (st
->st_shared
.ptr
!= NULL
)
2888 /* PFS: include the g^xy */
2889 prf_our
->get_bytes(prf_our
, st
->st_shared
, NULL
);
2890 prf_peer
->get_bytes(prf_peer
, st
->st_shared
, NULL
);
2892 prf_our
->get_bytes(prf_our
, protoid_chunk
, NULL
);
2893 prf_peer
->get_bytes(prf_peer
, protoid_chunk
, NULL
);
2895 prf_our
->get_bytes(prf_our
, spi_our
, NULL
);
2896 prf_peer
->get_bytes(prf_peer
, spi_peer
, NULL
);
2898 prf_our
->get_bytes(prf_our
, st
->st_ni
, NULL
);
2899 prf_peer
->get_bytes(prf_peer
, st
->st_ni
, NULL
);
2901 prf_our
->get_bytes(prf_our
, st
->st_nr
, keymat_i_our
);
2902 prf_peer
->get_bytes(prf_peer
, st
->st_nr
, keymat_i_peer
);
2904 i
+= prf_block_size
;
2905 if (i
>= needed_space
)
2910 /* more keying material needed: prepare to go around again */
2911 prf_our
->get_bytes(prf_our
, keymat_our
, NULL
);
2912 prf_peer
->get_bytes(prf_peer
, keymat_peer
, NULL
);
2914 prf_our
->destroy(prf_our
);
2915 prf_peer
->destroy(prf_peer
);
2918 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2919 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2922 static void compute_keymats(struct state
*st
)
2924 if (st
->st_ah
.present
)
2925 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2926 if (st
->st_esp
.present
)
2927 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2930 /* State Transition Functions.
2932 * The definition of state_microcode_table in demux.c is a good
2933 * overview of these routines.
2935 * - Called from process_packet; result handled by complete_state_transition
2936 * - struct state_microcode member "processor" points to these
2937 * - these routine definitionss are in state order
2938 * - these routines must be restartable from any point of error return:
2939 * beware of memory allocated before any error.
2940 * - output HDR is usually emitted by process_packet (if state_microcode
2941 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2943 * The transition functions' functions include:
2944 * - process and judge payloads
2945 * - update st_iv (result of decryption is in st_new_iv)
2946 * - build reply packet
2949 /* Handle a Main Mode Oakley first packet (responder side).
2952 stf_status
main_inI1_outR1(struct msg_digest
*md
)
2954 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2956 struct connection
*c
;
2957 struct isakmp_proposal proposal
;
2958 pb_stream proposal_pbs
;
2960 u_int32_t ipsecdoisit
;
2961 lset_t policy
= LEMPTY
;
2962 int vids_to_send
= 0;
2964 /* We preparse the peer's proposal in order to determine
2965 * the requested authentication policy (RSA or PSK)
2967 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2968 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2970 backup_pbs(&proposal_pbs
);
2971 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2972 , proposal
.isap_notrans
, &policy
));
2973 restore_pbs(&proposal_pbs
);
2975 /* We are only considering candidate connections that match
2976 * the requested authentication policy (RSA or PSK)
2978 c
= find_host_connection(&md
->iface
->addr
, pluto_port
2979 , &md
->sender
, md
->sender_port
, policy
);
2981 if (c
== NULL
&& md
->iface
->ike_float
)
2983 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
2984 , &md
->sender
, md
->sender_port
, policy
);
2989 /* See if a wildcarded connection can be found.
2990 * We cannot pick the right connection, so we're making a guess.
2991 * All Road Warrior connections are fair game:
2992 * we pick the first we come across (if any).
2993 * If we don't find any, we pick the first opportunistic
2994 * with the smallest subnet that includes the peer.
2995 * There is, of course, no necessary relationship between
2996 * an Initiator's address and that of its client,
2997 * but Food Groups kind of assumes one.
3000 struct connection
*d
;
3002 d
= find_host_connection(&md
->iface
->addr
3003 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
3005 for (; d
!= NULL
; d
= d
->hp_next
)
3007 if (d
->kind
== CK_GROUP
)
3013 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
3015 /* must be Road Warrior: we have a winner */
3020 /* Opportunistic or Shunt: pick tightest match */
3021 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
3022 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
3030 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3031 " but no connection has been authorized%s%s"
3032 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
3033 , (policy
!= LEMPTY
) ?
" with policy=" : ""
3034 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
3035 /* XXX notification is in order! */
3038 else if (c
->kind
!= CK_TEMPLATE
)
3040 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3041 " but \"%s\" forbids connection"
3042 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
3043 /* XXX notification is in order! */
3048 /* Create a temporary connection that is a copy of this one.
3049 * His ID isn't declared yet.
3051 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
3054 else if (c
->kind
== CK_TEMPLATE
)
3056 /* Create an instance
3057 * This is a rare case: wildcard peer ID but static peer IP address
3059 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
3063 md
->st
= st
= new_state();
3064 st
->st_connection
= c
;
3065 set_cur_state(st
); /* (caller will reset cur_state) */
3066 st
->st_try
= 0; /* not our job to try again from start */
3067 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
3069 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
3070 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
3072 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3074 st
->st_doi
= ISAKMP_DOI_IPSEC
;
3075 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
3077 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
3079 plog("responding to Main Mode from unknown peer %s:%u"
3080 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
3082 else if (c
->kind
== CK_INSTANCE
)
3084 plog("responding to Main Mode from unknown peer %s"
3085 , ip_str(&c
->spd
.that
.host_addr
));
3089 plog("responding to Main Mode");
3092 /* parse_isakmp_sa also spits out a winning SA into our reply,
3093 * so we have to build our md->reply and emit HDR before calling it.
3096 /* determine how many Vendor ID payloads we will be sending */
3099 if (SEND_CISCO_UNITY_VID
)
3105 /* always send DPD Vendor ID */
3107 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3111 * We can't leave this to comm_handle() because we must
3112 * fill in the cookie.
3115 struct isakmp_hdr r_hdr
= md
->hdr
;
3117 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
3118 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
3119 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
3120 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
3121 return STF_INTERNAL_ERROR
;
3124 /* start of SA out */
3126 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
3128 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
3130 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
3131 return STF_INTERNAL_ERROR
;
3134 /* SA body in and out */
3135 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
3136 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
3138 /* if enabled send Pluto Vendor ID */
3141 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3142 , &md
->rbody
, VID_STRONGSWAN
))
3144 return STF_INTERNAL_ERROR
;
3148 /* if enabled send Cisco Unity Vendor ID */
3149 if (SEND_CISCO_UNITY_VID
)
3151 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3152 , &md
->rbody
, VID_CISCO_UNITY
))
3154 return STF_INTERNAL_ERROR
;
3159 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3163 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3164 , &md
->rbody
, VID_OPENPGP
))
3166 return STF_INTERNAL_ERROR
;
3170 /* Announce our ability to do eXtended AUTHentication to the peer */
3173 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3174 , &md
->rbody
, VID_MISC_XAUTH
))
3176 return STF_INTERNAL_ERROR
;
3180 /* Announce our ability to do Dead Peer Detection to the peer */
3181 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3182 , &md
->rbody
, VID_MISC_DPD
))
3184 return STF_INTERNAL_ERROR
;
3187 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3189 /* reply if NAT-Traversal draft is supported */
3190 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3192 if (st
->nat_traversal
3193 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3194 , &md
->rbody
, md
->nat_traversal_vid
))
3196 return STF_INTERNAL_ERROR
;
3200 close_message(&md
->rbody
);
3202 /* save initiator SA for HASH */
3203 free(st
->st_p1isa
.ptr
);
3204 st
->st_p1isa
= chunk_create(sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
));
3205 st
->st_p1isa
= chunk_clone(st
->st_p1isa
);
3210 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3211 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3213 * The following are not yet implemented:
3214 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3215 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3216 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3218 * We must verify that the proposal received matches one we sent.
3220 stf_status
main_inR1_outI2(struct msg_digest
*md
)
3222 struct state
*const st
= md
->st
;
3224 u_int8_t np
= ISAKMP_NEXT_NONE
;
3226 /* verify echoed SA */
3228 u_int32_t ipsecdoisit
;
3229 pb_stream proposal_pbs
;
3230 struct isakmp_proposal proposal
;
3231 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3233 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3234 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3235 if (proposal
.isap_notrans
!= 1)
3237 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3238 , (unsigned)proposal
.isap_notrans
);
3239 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3241 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3242 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3245 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3247 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3248 plog("enabling possible NAT-traversal with method %s"
3249 , bitnamesof(natt_type_bitnames
, st
->nat_traversal
));
3251 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3253 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3254 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3257 /**************** build output packet HDR;KE;Ni ****************/
3260 * We can't leave this to comm_handle() because the isa_np
3261 * depends on the type of Auth (eventually).
3263 echo_hdr(md
, FALSE
, ISAKMP_NEXT_KE
);
3266 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_oakley
.group
3267 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3268 return STF_INTERNAL_ERROR
;
3272 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
3273 , (cur_debugging
& IMPAIR_BUST_MI2
)? ISAKMP_NEXT_VID
: np
, "Ni"))
3274 return STF_INTERNAL_ERROR
;
3276 if (cur_debugging
& IMPAIR_BUST_MI2
)
3278 /* generate a pointless large VID payload to push message over MTU */
3281 if (!out_generic(np
, &isakmp_vendor_id_desc
, &md
->rbody
, &vid_pbs
))
3282 return STF_INTERNAL_ERROR
;
3283 if (!out_zero(1500 /*MTU?*/, &vid_pbs
, "Filler VID"))
3284 return STF_INTERNAL_ERROR
;
3285 close_output_pbs(&vid_pbs
);
3289 if (!build_and_ship_nonce(&st
->st_ni
, &md
->rbody
, np
, "Ni"))
3290 return STF_INTERNAL_ERROR
;
3293 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3295 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE
, &md
->rbody
, md
))
3296 return STF_INTERNAL_ERROR
;
3299 /* finish message */
3300 close_message(&md
->rbody
);
3302 /* Reinsert the state, using the responder cookie we just received */
3304 memcpy(st
->st_rcookie
, md
->hdr
.isa_rcookie
, COOKIE_SIZE
);
3305 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3311 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3313 * The following are not yet implemented:
3314 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3315 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3317 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3318 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3320 stf_status
main_inI2_outR2(struct msg_digest
*md
)
3322 struct state
*const st
= md
->st
;
3323 pb_stream
*keyex_pbs
= &md
->chain
[ISAKMP_NEXT_KE
]->pbs
;
3325 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3326 bool RSA_auth
= st
->st_oakley
.auth
== OAKLEY_RSA_SIG
3327 || st
->st_oakley
.auth
== XAUTHInitRSA
3328 || st
->st_oakley
.auth
== XAUTHRespRSA
;
3329 bool send_cr
= !no_cr_send
&& RSA_auth
&& !has_preloaded_public_key(st
);
3331 u_int8_t np
= ISAKMP_NEXT_NONE
;
3334 RETURN_STF_FAILURE(accept_KE(&st
->st_gi
, "Gi", st
->st_oakley
.group
, keyex_pbs
));
3337 RETURN_STF_FAILURE(accept_nonce(md
, &st
->st_ni
, "Ni"));
3339 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3341 nat_traversal_natd_lookup(md
);
3343 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3344 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3346 if (st
->nat_traversal
)
3348 nat_traversal_show_result(st
->nat_traversal
, md
->sender_port
);
3350 if (st
->nat_traversal
& NAT_T_WITH_KA
)
3352 nat_traversal_new_ka_event();
3355 /* decode certificate requests */
3356 st
->st_connection
->got_certrequest
= FALSE
;
3357 decode_cr(md
, st
->st_connection
);
3359 /**************** build output packet HDR;KE;Nr ****************/
3364 if (!build_and_ship_KE(st
, &st
->st_gr
, st
->st_oakley
.group
3365 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3366 return STF_INTERNAL_ERROR
;
3370 if (!build_and_ship_nonce(&st
->st_nr
, &md
->rbody
3371 , (cur_debugging
& IMPAIR_BUST_MR2
)? ISAKMP_NEXT_VID
3372 : (send_cr? ISAKMP_NEXT_CR
: np
), "Nr"))
3373 return STF_INTERNAL_ERROR
;
3375 if (cur_debugging
& IMPAIR_BUST_MR2
)
3377 /* generate a pointless large VID payload to push message over MTU */
3380 if (!out_generic((send_cr
)? ISAKMP_NEXT_CR
: np
,
3381 &isakmp_vendor_id_desc
, &md
->rbody
, &vid_pbs
))
3382 return STF_INTERNAL_ERROR
;
3383 if (!out_zero(1500 /*MTU?*/, &vid_pbs
, "Filler VID"))
3384 return STF_INTERNAL_ERROR
;
3385 close_output_pbs(&vid_pbs
);
3389 if (!build_and_ship_nonce(&st
->st_nr
, &md
->rbody
,
3390 (send_cr
)? ISAKMP_NEXT_CR
: np
, "Nr"))
3391 return STF_INTERNAL_ERROR
;
3397 if (st
->st_connection
->kind
== CK_PERMANENT
)
3399 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3400 , st
->st_connection
->spd
.that
.ca
3402 return STF_INTERNAL_ERROR
;
3406 generalName_t
*ca
= NULL
;
3408 if (collect_rw_ca_candidates(md
, &ca
))
3412 for (gn
= ca
; gn
!= NULL
; gn
= gn
->next
)
3414 if (!build_and_ship_CR(CERT_X509_SIGNATURE
, gn
->name
3416 , gn
->next
== NULL ? np
: ISAKMP_NEXT_CR
))
3417 return STF_INTERNAL_ERROR
;
3419 free_generalNames(ca
, FALSE
);
3423 if (!build_and_ship_CR(CERT_X509_SIGNATURE
, chunk_empty
3425 return STF_INTERNAL_ERROR
;
3430 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3432 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE
, &md
->rbody
, md
))
3433 return STF_INTERNAL_ERROR
;
3436 /* finish message */
3437 close_message(&md
->rbody
);
3439 /* next message will be encrypted, but not this one.
3440 * We could defer this calculation.
3442 compute_dh_shared(st
, st
->st_gi
);
3443 if (!generate_skeyids_iv(st
))
3444 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3451 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3452 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3454 * The following are not yet implemented.
3455 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3457 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3460 stf_status
main_inR2_outI3(struct msg_digest
*md
)
3462 struct state
*const st
= md
->st
;
3463 pb_stream
*const keyex_pbs
= &md
->chain
[ISAKMP_NEXT_KE
]->pbs
;
3464 pb_stream id_pbs
; /* ID Payload; also used for hash calculation */
3466 certpolicy_t cert_policy
= st
->st_connection
->spd
.this.sendcert
;
3467 cert_t mycert
= st
->st_connection
->spd
.this.cert
;
3468 bool requested
, send_cert
, send_cr
;
3470 bool RSA_auth
= st
->st_oakley
.auth
== OAKLEY_RSA_SIG
3471 || st
->st_oakley
.auth
== XAUTHInitRSA
3472 || st
->st_oakley
.auth
== XAUTHRespRSA
;
3474 int auth_payload
= RSA_auth ? ISAKMP_NEXT_SIG
: ISAKMP_NEXT_HASH
;
3477 RETURN_STF_FAILURE(accept_KE(&st
->st_gr
, "Gr", st
->st_oakley
.group
, keyex_pbs
));
3480 RETURN_STF_FAILURE(accept_nonce(md
, &st
->st_nr
, "Nr"));
3482 /* decode certificate requests */
3483 st
->st_connection
->got_certrequest
= FALSE
;
3484 decode_cr(md
, st
->st_connection
);
3486 /* free collected certificate requests since as initiator
3487 * we don't heed them anyway
3489 free_generalNames(st
->st_connection
->requested_ca
, TRUE
);
3490 st
->st_connection
->requested_ca
= NULL
;
3492 /* send certificate if auth is RSA, we have one and we want
3493 * or are requested to send it
3495 requested
= cert_policy
== CERT_SEND_IF_ASKED
3496 && st
->st_connection
->got_certrequest
;
3497 send_cert
= RSA_auth
&& mycert
.type
!= CERT_NONE
3498 && (cert_policy
== CERT_ALWAYS_SEND
|| requested
);
3500 /* send certificate request if we don't have a preloaded RSA public key */
3501 send_cr
= !no_cr_send
&& send_cert
&& !has_preloaded_public_key(st
);
3503 /* done parsing; initialize crypto */
3504 compute_dh_shared(st
, st
->st_gr
);
3505 if (!generate_skeyids_iv(st
))
3506 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3508 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3510 nat_traversal_natd_lookup(md
);
3512 if (st
->nat_traversal
)
3514 nat_traversal_show_result(st
->nat_traversal
, md
->sender_port
);
3516 if (st
->nat_traversal
& NAT_T_WITH_KA
)
3518 nat_traversal_new_ka_event();
3521 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3522 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3528 struct isakmp_ipsec_id id_hd
;
3531 build_id_payload(&id_hd
, &id_b
, &st
->st_connection
->spd
.this);
3532 id_hd
.isaiid_np
= (send_cert
)? ISAKMP_NEXT_CERT
: auth_payload
;
3533 if (!out_struct(&id_hd
, &isakmp_ipsec_identification_desc
, &md
->rbody
, &id_pbs
)
3534 || !out_chunk(id_b
, &id_pbs
, "my identity"))
3535 return STF_INTERNAL_ERROR
;
3536 close_output_pbs(&id_pbs
);
3543 DBG_log("our certificate policy is %N", cert_policy_names
, cert_policy
)
3545 if (mycert
.type
!= CERT_NONE
)
3547 const char *request_text
= "";
3549 if (cert_policy
== CERT_SEND_IF_ASKED
)
3550 request_text
= (send_cert
)?
"upon request":"without request";
3551 plog("we have a cert %s sending it %s"
3552 , send_cert?
"and are":"but are not", request_text
);
3556 plog("we don't have a cert");
3563 struct isakmp_cert cert_hd
;
3564 cert_hd
.isacert_np
= (send_cr
)? ISAKMP_NEXT_CR
: ISAKMP_NEXT_SIG
;
3565 cert_hd
.isacert_type
= mycert
.type
;
3567 if (!out_struct(&cert_hd
, &isakmp_ipsec_certificate_desc
, &md
->rbody
, &cert_pbs
))
3568 return STF_INTERNAL_ERROR
;
3569 if (!out_chunk(get_mycert(mycert
), &cert_pbs
, "CERT"))
3570 return STF_INTERNAL_ERROR
;
3571 close_output_pbs(&cert_pbs
);
3577 if (!build_and_ship_CR(mycert
.type
, st
->st_connection
->spd
.that
.ca
3578 , &md
->rbody
, ISAKMP_NEXT_SIG
))
3579 return STF_INTERNAL_ERROR
;
3582 /* HASH_I or SIG_I out */
3584 u_char hash_val
[MAX_DIGEST_LEN
];
3585 size_t hash_len
= main_mode_hash(st
, hash_val
, TRUE
, &id_pbs
);
3587 if (auth_payload
== ISAKMP_NEXT_HASH
)
3590 if (!out_generic_raw(ISAKMP_NEXT_NONE
, &isakmp_hash_desc
, &md
->rbody
3591 , hash_val
, hash_len
, "HASH_I"))
3592 return STF_INTERNAL_ERROR
;
3597 u_char sig_val
[RSA_MAX_OCTETS
];
3598 size_t sig_len
= RSA_sign_hash(st
->st_connection
3599 , sig_val
, hash_val
, hash_len
);
3603 loglog(RC_LOG_SERIOUS
, "unable to locate my private key for RSA Signature");
3604 return STF_FAIL
+ AUTHENTICATION_FAILED
;
3607 if (!out_generic_raw(ISAKMP_NEXT_NONE
, &isakmp_signature_desc
3608 , &md
->rbody
, sig_val
, sig_len
, "SIG_I"))
3609 return STF_INTERNAL_ERROR
;
3613 /* encrypt message, except for fixed part of header */
3615 /* st_new_iv was computed by generate_skeyids_iv */
3616 if (!encrypt_message(&md
->rbody
, st
))
3617 return STF_INTERNAL_ERROR
; /* ??? we may be partly committed */
3622 /* Shared logic for asynchronous lookup of DNS KEY records.
3623 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3626 enum key_oppo_step
{
3634 struct key_continuation
{
3635 struct adns_continuation ac
; /* common prefix */
3636 struct msg_digest
*md
;
3637 enum key_oppo_step step
;
3642 typedef stf_status (key_tail_fn
)(struct msg_digest
*md
3643 , struct key_continuation
*kc
);
3645 static void report_key_dns_failure(struct id
*id
, err_t ugh
)
3647 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
3649 (void) idtoa(id
, id_buf
, sizeof(id_buf
));
3650 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
3651 "; DNS search for KEY failed (%s)", id_buf
, ugh
);
3655 /* Processs the Main Mode ID Payload and the Authenticator
3656 * (Hash or Signature Payload).
3657 * If a DNS query is still needed to get the other host's public key,
3658 * the query is initiated and STF_SUSPEND is returned.
3659 * Note: parameter kc is a continuation containing the results from
3660 * the previous DNS query, or NULL indicating no query has been issued.
3663 main_id_and_auth(struct msg_digest
*md
3664 , bool initiator
/* are we the Initiator? */
3665 , cont_fn_t cont_fn
/* continuation function */
3666 , const struct key_continuation
*kc
/* current state, can be NULL */
3669 struct state
*st
= md
->st
;
3670 u_char hash_val
[MAX_DIGEST_LEN
];
3673 stf_status r
= STF_OK
;
3676 if (!decode_peer_id(md
, &peer
))
3677 return STF_FAIL
+ INVALID_ID_INFORMATION
;
3679 /* Hash the ID Payload.
3680 * main_mode_hash requires idpl->cur to be at end of payload
3681 * so we temporarily set if so.
3684 pb_stream
*idpl
= &md
->chain
[ISAKMP_NEXT_ID
]->pbs
;
3685 u_int8_t
*old_cur
= idpl
->cur
;
3687 idpl
->cur
= idpl
->roof
;
3688 hash_len
= main_mode_hash(st
, hash_val
, !initiator
, idpl
);
3689 idpl
->cur
= old_cur
;
3692 switch (st
->st_oakley
.auth
)
3694 case OAKLEY_PRESHARED_KEY
:
3695 case XAUTHInitPreShared
:
3696 case XAUTHRespPreShared
: