1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29 #include <sys/time.h> /* for gettimeofday */
32 #include <ipsec_policy.h>
34 #include "constants.h"
43 #include "smartcard.h"
44 #include "connections.h"
47 #include "demux.h" /* needs packet.h */
48 #include "adns.h" /* needs <resolv.h> */
49 #include "dnskey.h" /* needs keys.h and adns.h */
57 #include "ipsec_doi.h" /* needs demux.h and state.h */
65 #include "crypto.h" /* requires sha1.h and md5.h */
69 #include "kernel_alg.h"
70 #include "nat_traversal.h"
74 * are we sending Pluto's Vendor ID?
77 #define SEND_PLUTO_VID 1
79 #define SEND_PLUTO_VID 0
80 #endif /* !VENDORID */
83 * are we sending an XAUTH VID?
86 #define SEND_XAUTH_VID 1
87 #else /* !XAUTH_VID */
88 #define SEND_XAUTH_VID 0
89 #endif /* !XAUTH_VID */
92 * are we sending a Cisco Unity VID?
95 #define SEND_CISCO_UNITY_VID 1
96 #else /* !CISCO_QUIRKS */
97 #define SEND_CISCO_UNITY_VID 0
98 #endif /* !CISCO_QUIRKS */
100 /* MAGIC: perform f, a function that returns notification_t
101 * and return from the ENCLOSING stf_status returning function if it fails.
103 #define RETURN_STF_FAILURE(f) \
104 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
106 /* create output HDR as replica of input HDR */
108 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
110 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
112 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
114 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
115 /* some day, we may have to set r_hdr.isa_version */
117 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
118 impossible(); /* surely must have room and be well-formed */
121 /* Compute DH shared secret from our local secret and the peer's public value.
122 * We make the leap that the length should be that of the group
123 * (see quoted passage at start of ACCEPT_KE).
126 compute_dh_shared(struct state
*st
, const chunk_t g
127 , const struct oakley_group_desc
*group
)
129 MP_INT mp_g
, mp_shared
;
130 struct timeval tv0
, tv1
;
131 unsigned long tv_diff
;
133 gettimeofday(&tv0
, NULL
);
134 passert(st
->st_sec_in_use
);
135 n_to_mpz(&mp_g
, g
.ptr
, g
.len
);
136 mpz_init(&mp_shared
);
137 mpz_powm(&mp_shared
, &mp_g
, &st
->st_sec
, group
->modulus
);
139 freeanychunk(st
->st_shared
); /* happens in odd error cases */
140 st
->st_shared
= mpz_to_n(&mp_shared
, group
->bytes
);
141 mpz_clear(&mp_shared
);
142 gettimeofday(&tv1
, NULL
);
143 tv_diff
=(tv1
.tv_sec
- tv0
.tv_sec
) * 1000000 + (tv1
.tv_usec
- tv0
.tv_usec
);
145 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
146 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
149 /* if took more than 200 msec ... */
150 if (tv_diff
> 200000) {
151 loglog(RC_LOG_SERIOUS
, "WARNING: compute_dh_shared(): for %s took "
153 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
157 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
160 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
161 * the corresponding public value (g). This is emitted as a KE payload.
164 build_and_ship_KE(struct state
*st
, chunk_t
*g
165 , const struct oakley_group_desc
*group
, pb_stream
*outs
, u_int8_t np
)
167 if (!st
->st_sec_in_use
)
169 u_char tmp
[LOCALSECRETSIZE
];
172 get_rnd_bytes(tmp
, LOCALSECRETSIZE
);
173 st
->st_sec_in_use
= TRUE
;
174 n_to_mpz(&st
->st_sec
, tmp
, LOCALSECRETSIZE
);
177 mpz_powm(&mp_g
, &groupgenerator
, &st
->st_sec
, group
->modulus
);
178 freeanychunk(*g
); /* happens in odd error cases */
179 *g
= mpz_to_n(&mp_g
, group
->bytes
);
182 DBG_dump("Local DH secret:\n", tmp
, LOCALSECRETSIZE
);
183 DBG_dump_chunk("Public DH value sent:\n", *g
));
185 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
190 * Check and accept DH public value (Gi or Gr) from peer's message.
191 * According to RFC2409 "The Internet key exchange (IKE)" 5:
192 * The Diffie-Hellman public value passed in a KE payload, in either
193 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
194 * Diffie-Hellman group enforced, if necessary, by pre-pending the
197 static notification_t
198 accept_KE(chunk_t
*dest
, const char *val_name
199 , const struct oakley_group_desc
*gr
202 if (pbs_left(pbs
) != gr
->bytes
)
204 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
205 , (unsigned) pbs_left(pbs
), (unsigned) gr
->bytes
);
206 /* XXX Could send notification back */
207 return INVALID_KEY_INFORMATION
;
209 clonereplacechunk(*dest
, pbs
->cur
, pbs_left(pbs
), val_name
);
210 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
211 return NOTHING_WRONG
;
216 * Check and accept optional Quick Mode KE payload for PFS.
217 * Extends ACCEPT_PFS to check whether KE is allowed or required.
219 static notification_t
220 accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
221 , const char *val_name
, const char *msg_name
)
223 struct state
*st
= md
->st
;
224 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
228 if (st
->st_pfs_group
!= NULL
)
230 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
231 return INVALID_KEY_INFORMATION
;
236 if (st
->st_pfs_group
== NULL
)
238 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
240 return INVALID_KEY_INFORMATION
;
242 if (ke_pd
->next
!= NULL
)
244 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
245 return INVALID_KEY_INFORMATION
; /* ??? */
247 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
249 return NOTHING_WRONG
;
253 build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
257 setchunk(*n
, alloc_bytes(DEFAULT_NONCE_SIZE
, name
), DEFAULT_NONCE_SIZE
);
258 get_rnd_bytes(n
->ptr
, DEFAULT_NONCE_SIZE
);
259 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
263 collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
265 struct connection
*d
= find_host_connection(&md
->iface
->addr
266 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
268 for (; d
!= NULL
; d
= d
->hp_next
)
270 /* must be a road warrior connection */
271 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
272 && d
->spd
.that
.ca
.ptr
!= NULL
)
275 bool new_entry
= TRUE
;
277 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
279 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
287 gn
= alloc_thing(generalName_t
, "generalName");
288 gn
->kind
= GN_DIRECTORY_NAME
;
289 gn
->name
= d
->spd
.that
.ca
;
299 build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
, u_int8_t np
)
302 struct isakmp_cr cr_hd
;
304 cr_hd
.isacr_type
= type
;
306 /* build CR header */
307 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
312 /* build CR body containing the distinguished name of the CA */
313 if (!out_chunk(ca
, &cr_pbs
, "CA"))
316 close_output_pbs(&cr_pbs
);
320 /* Send a notification to the peer. We could decide
321 * whether to send the notification, based on the type and the
322 * destination, if we care to.
325 send_notification(struct state
*sndst
, u_int16_t type
, struct state
*encst
,
326 msgid_t msgid
, u_char
*icookie
, u_char
*rcookie
,
327 u_char
*spi
, size_t spisize
, u_char protoid
)
330 pb_stream pbs
, r_hdr_pbs
;
331 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
332 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
334 passert((sndst
) && (sndst
->st_connection
));
336 plog("sending %snotification %s to %s:%u"
337 , encst ?
"encrypted " : ""
338 , enum_name(¬ification_names
, type
)
339 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
340 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
342 memset(buffer
, 0, sizeof(buffer
));
343 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
347 struct isakmp_hdr hdr
;
349 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
350 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
351 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
352 hdr
.isa_msgid
= msgid
;
353 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
355 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
357 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
358 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
362 /* HASH -- value to be filled later */
366 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
369 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
371 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
373 close_output_pbs(&hash_pbs
);
374 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
377 /* Notification Payload */
380 struct isakmp_notification isan
;
382 isan
.isan_doi
= ISAKMP_DOI_IPSEC
;
383 isan
.isan_np
= ISAKMP_NEXT_NONE
;
384 isan
.isan_type
= type
;
385 isan
.isan_spisize
= spisize
;
386 isan
.isan_protoid
= protoid
;
388 if (!out_struct(&isan
, &isakmp_notification_desc
, &r_hdr_pbs
, ¬_pbs
)
389 || !out_raw(spi
, spisize
, ¬_pbs
, "spi"))
391 close_output_pbs(¬_pbs
);
394 /* calculate hash value and patch into Hash Payload */
398 hmac_init_chunk(&ctx
, encst
->st_oakley
.hasher
, encst
->st_skeyid_a
);
399 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
400 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
401 hmac_final(r_hashval
, &ctx
);
404 DBG_log("HASH computed:");
405 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
409 /* Encrypt message (preserve st_iv and st_new_iv) */
412 u_char old_iv
[MAX_DIGEST_LEN
];
413 u_char new_iv
[MAX_DIGEST_LEN
];
415 u_int old_iv_len
= encst
->st_iv_len
;
416 u_int new_iv_len
= encst
->st_new_iv_len
;
418 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
421 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
422 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
424 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
426 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
427 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
429 init_phase2_iv(encst
, &msgid
);
430 if (!encrypt_message(&r_hdr_pbs
, encst
))
433 /* restore preserved st_iv and st_new_iv */
434 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
435 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
436 encst
->st_iv_len
= old_iv_len
;
437 encst
->st_new_iv_len
= new_iv_len
;
441 close_output_pbs(&r_hdr_pbs
);
444 /* Send packet (preserve st_tpacket) */
446 chunk_t saved_tpacket
= sndst
->st_tpacket
;
448 setchunk(sndst
->st_tpacket
, pbs
.start
, pbs_offset(&pbs
));
449 send_packet(sndst
, "ISAKMP notify");
450 sndst
->st_tpacket
= saved_tpacket
;
455 send_notification_from_state(struct state
*st
, enum state_kind state
,
462 if (state
== STATE_UNDEFINED
)
463 state
= st
->st_state
;
467 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
468 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
)))
470 loglog(RC_LOG_SERIOUS
,
471 "no Phase1 state for Quick mode notification");
474 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
475 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
477 else if (IS_ISAKMP_ENCRYPTED(state
) && st
->st_enc_key
.ptr
!= NULL
)
479 send_notification(st
, type
, st
, generate_msgid(st
),
480 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
484 /* no ISAKMP SA established - don't encrypt notification */
485 send_notification(st
, type
, NULL
, 0,
486 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
491 send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
494 * Create a dummy state to be able to use send_packet in
498 * st_connection->that.host_addr
499 * st_connection->that.host_port
500 * st_connection->interface
503 struct connection cnx
;
507 memset(&st
, 0, sizeof(st
));
508 memset(&cnx
, 0, sizeof(cnx
));
509 st
.st_connection
= &cnx
;
510 cnx
.spd
.that
.host_addr
= md
->sender
;
511 cnx
.spd
.that
.host_port
= md
->sender_port
;
512 cnx
.interface
= md
->iface
;
514 send_notification(&st
, type
, NULL
, 0,
515 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
518 /* Send a Delete Notification to announce deletion of ISAKMP SA or
519 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
520 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
523 send_delete(struct state
*st
)
530 ip_said said
[EM_MAXRELSPIS
];
533 *r_hashval
, /* where in reply to jam hash value */
534 *r_hash_start
; /* start of what is to be hashed */
535 bool isakmp_sa
= FALSE
;
537 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
539 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
542 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
546 if (st
->st_ah
.present
)
548 ns
->spi
= st
->st_ah
.our_spi
;
549 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
550 ns
->proto
= PROTO_IPSEC_AH
;
553 if (st
->st_esp
.present
)
555 ns
->spi
= st
->st_esp
.our_spi
;
556 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
557 ns
->proto
= PROTO_IPSEC_ESP
;
561 passert(ns
!= said
); /* there must be some SAs to delete */
563 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
570 return; /* nothing to do */
573 msgid
= generate_msgid(p1st
);
576 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
580 struct isakmp_hdr hdr
;
582 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
583 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
584 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
585 hdr
.isa_msgid
= msgid
;
586 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
587 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
588 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
589 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
593 /* HASH -- value to be filled later */
597 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
599 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
600 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
602 close_output_pbs(&hash_pbs
);
603 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
606 /* Delete Payloads */
610 struct isakmp_delete isad
;
611 u_char isakmp_spi
[2*COOKIE_SIZE
];
613 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
614 isad
.isad_np
= ISAKMP_NEXT_NONE
;
615 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
616 isad
.isad_protoid
= PROTO_ISAKMP
;
619 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
620 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
622 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
623 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
625 close_output_pbs(&del_pbs
);
633 struct isakmp_delete isad
;
636 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
637 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
638 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
639 isad
.isad_protoid
= ns
->proto
;
642 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
643 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
645 close_output_pbs(&del_pbs
);
649 /* calculate hash value and patch into Hash Payload */
652 hmac_init_chunk(&ctx
, p1st
->st_oakley
.hasher
, p1st
->st_skeyid_a
);
653 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
654 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
655 hmac_final(r_hashval
, &ctx
);
658 DBG_log("HASH(1) computed:");
659 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
663 /* Do a dance to avoid needing a new state object.
664 * We use the Phase 1 State. This is the one with right
666 * The tricky bits are:
667 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
668 * - we need to preserve (save/restore) st_tpacket.
671 u_char old_iv
[MAX_DIGEST_LEN
];
672 chunk_t saved_tpacket
= p1st
->st_tpacket
;
674 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
675 init_phase2_iv(p1st
, &msgid
);
677 if (!encrypt_message(&r_hdr_pbs
, p1st
))
680 setchunk(p1st
->st_tpacket
, reply_pbs
.start
, pbs_offset(&reply_pbs
));
681 send_packet(p1st
, "delete notify");
682 p1st
->st_tpacket
= saved_tpacket
;
684 /* get back old IV for this state */
685 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
690 accept_delete(struct state
*st
, struct msg_digest
*md
, struct payload_digest
*p
)
692 struct isakmp_delete
*d
= &(p
->payload
.delete);
698 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
702 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
704 /* can't happen (if msg is encrypt), but just to be sure */
705 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
706 "ISAKMP SA not established");
710 if (d
->isad_nospi
== 0)
712 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
716 switch (d
->isad_protoid
)
719 sizespi
= 2 * COOKIE_SIZE
;
722 case PROTO_IPSEC_ESP
:
723 sizespi
= sizeof(ipsec_spi_t
);
726 /* nothing interesting to delete */
729 loglog(RC_LOG_SERIOUS
730 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
731 , enum_show(&protocol_names
, d
->isad_protoid
));
735 if (d
->isad_spisize
!= sizespi
)
737 loglog(RC_LOG_SERIOUS
738 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
739 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
743 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
745 loglog(RC_LOG_SERIOUS
746 , "ignoring Delete SA payload: invalid payload size");
750 for (i
= 0; i
< d
->isad_nospi
; i
++)
752 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
754 if (d
->isad_protoid
== PROTO_ISAKMP
)
759 struct state
*dst
= find_state(spi
/*iCookie*/
760 , spi
+COOKIE_SIZE
/*rCookie*/
761 , &st
->st_connection
->spd
.that
.host_addr
766 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
767 "ISAKMP SA not found (maybe expired)");
769 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
771 /* we've not authenticated the relevant identities */
772 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
773 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
777 struct connection
*oldc
;
779 oldc
= cur_connection
;
780 set_cur_connection(dst
->st_connection
);
782 if (nat_traversal_enabled
)
783 nat_traversal_change_port_lookup(md
, dst
);
785 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
786 "deleting ISAKMP State #%lu", dst
->st_serialno
);
788 set_cur_connection(oldc
);
797 struct state
*dst
= find_phase2_state_to_delete(st
799 , *(ipsec_spi_t
*)spi
/* network order */
804 loglog(RC_LOG_SERIOUS
805 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
806 , enum_show(&protocol_names
, d
->isad_protoid
)
807 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
808 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
812 struct connection
*rc
= dst
->st_connection
;
813 struct connection
*oldc
;
815 oldc
= cur_connection
;
816 set_cur_connection(rc
);
818 if (nat_traversal_enabled
)
819 nat_traversal_change_port_lookup(md
, dst
);
821 if (rc
->newest_ipsec_sa
== dst
->st_serialno
822 && (rc
->policy
& POLICY_UP
))
824 /* Last IPSec SA for a permanent connection that we
825 * have initiated. Replace it in a few seconds.
827 * Useful if the other peer is rebooting.
829 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
830 if (dst
->st_event
!= NULL
831 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
832 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
834 /* Patch from Angus Lees to ignore retransmited
837 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
838 "already replacing IPSEC State #%lu in %d seconds"
839 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
843 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
844 "replace IPSEC State #%lu in %d seconds"
845 , dst
->st_serialno
, DELETE_SA_DELAY
);
846 dst
->st_margin
= DELETE_SA_DELAY
;
848 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
853 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
854 "deleting IPSEC State #%lu"
855 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
860 /* reset connection */
861 set_cur_connection(oldc
);
867 /* The whole message must be a multiple of 4 octets.
868 * I'm not sure where this is spelled out, but look at
869 * rfc2408 3.6 Transform Payload.
870 * Note: it talks about 4 BYTE boundaries!
873 close_message(pb_stream
*pbs
)
875 size_t padding
= pad_up(pbs_offset(pbs
), 4);
878 (void) out_zero(padding
, pbs
, "message padding");
879 close_output_pbs(pbs
);
882 /* Initiate an Oakley Main Mode exchange.
884 * Note: this is not called from demux.c
887 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
888 , lset_t policy
, unsigned long try)
890 struct state
*st
= new_state();
891 pb_stream reply
; /* not actually a reply, but you know what I mean */
894 int vids_to_send
= 0;
896 /* set up new state */
897 st
->st_connection
= c
;
898 set_cur_state(st
); /* we must reset before exit */
899 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
900 st
->st_whack_sock
= whack_sock
;
902 st
->st_state
= STATE_MAIN_I1
;
904 /* determine how many Vendor ID payloads we will be sending */
907 if (SEND_CISCO_UNITY_VID
)
909 if (c
->spd
.this.cert
.type
== CERT_PGP
)
913 /* always send DPD Vendor ID */
915 if (nat_traversal_enabled
)
918 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
920 insert_state(st
); /* needs cookies, connection, and msgid (0) */
922 if (HAS_IPSEC_POLICY(policy
))
923 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
924 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
926 if (predecessor
== NULL
)
927 plog("initiating Main Mode");
929 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
932 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
936 struct isakmp_hdr hdr
;
938 zero(&hdr
); /* default to 0 */
939 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
940 hdr
.isa_np
= ISAKMP_NEXT_SA
;
941 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
942 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
943 /* R-cookie, flags and MessageID are left zero */
945 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
948 return STF_INTERNAL_ERROR
;
954 u_char
*sa_start
= rbody
.cur
;
956 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
957 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
960 return STF_INTERNAL_ERROR
;
963 /* save initiator SA for later HASH */
964 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
965 clonetochunk(st
->st_p1isa
, sa_start
, rbody
.cur
- sa_start
966 , "sa in main_outI1");
969 /* if enabled send Pluto Vendor ID */
972 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
973 , &rbody
, VID_STRONGSWAN
))
976 return STF_INTERNAL_ERROR
;
980 /* if enabled send Cisco Unity Vendor ID */
981 if (SEND_CISCO_UNITY_VID
)
983 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
984 , &rbody
, VID_CISCO_UNITY
))
987 return STF_INTERNAL_ERROR
;
990 /* if we have an OpenPGP certificate we assume an
991 * OpenPGP peer and have to send the Vendor ID
993 if (c
->spd
.this.cert
.type
== CERT_PGP
)
995 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
996 , &rbody
, VID_OPENPGP
))
999 return STF_INTERNAL_ERROR
;
1003 /* Announce our ability to do eXtended AUTHentication to the peer */
1006 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1007 , &rbody
, VID_MISC_XAUTH
))
1010 return STF_INTERNAL_ERROR
;
1014 /* Announce our ability to do Dead Peer Detection to the peer */
1016 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1017 , &rbody
, VID_MISC_DPD
))
1020 return STF_INTERNAL_ERROR
;
1024 if (nat_traversal_enabled
)
1026 /* Add supported NAT-Traversal VID */
1027 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1031 return STF_INTERNAL_ERROR
;
1035 close_message(&rbody
);
1036 close_output_pbs(&reply
);
1038 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
1039 , "reply packet for main_outI1");
1043 send_packet(st
, "main_outI1");
1045 /* Set up a retransmission event, half a minute henceforth */
1047 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1049 if (predecessor
!= NULL
)
1051 update_pending(predecessor
, st
);
1052 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1053 , "%s: initiate, replacing #%lu"
1054 , enum_name(&state_names
, st
->st_state
)
1055 , predecessor
->st_serialno
);
1059 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1060 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1067 ipsecdoi_initiate(int whack_sock
1068 , struct connection
*c
1071 , so_serial_t replacing
)
1073 /* If there's already an ISAKMP SA established, use that and
1074 * go directly to Quick Mode. We are even willing to use one
1075 * that is still being negotiated, but only if we are the Initiator
1076 * (thus we can be sure that the IDs are not going to change;
1077 * other issues around intent might matter).
1078 * Note: there is no way to initiate with a Road Warrior.
1080 struct state
*st
= find_phase1_state(c
1081 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1085 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1087 else if (HAS_IPSEC_POLICY(policy
))
1089 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1091 /* leave our Phase 2 negotiation pending */
1092 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1096 /* ??? we assume that peer_nexthop_sin isn't important:
1097 * we already have it from when we negotiated the ISAKMP SA!
1098 * It isn't clear what to do with the error return.
1100 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1105 close_any(whack_sock
);
1109 /* Replace SA with a fresh one that is similar
1111 * Shares some logic with ipsecdoi_initiate, but not the same!
1112 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1113 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1114 * ISAKMP SA if needed.
1115 * - duplicate whack fd, if live.
1116 * Does not delete the old state -- someone else will do that.
1119 ipsecdoi_replace(struct state
*st
, unsigned long try)
1121 int whack_sock
= dup_any(st
->st_whack_sock
);
1122 lset_t policy
= st
->st_policy
;
1124 if (IS_PHASE1(st
->st_state
))
1126 passert(!HAS_IPSEC_POLICY(policy
));
1127 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1131 /* Add features of actual old state to policy. This ensures
1132 * that rekeying doesn't downgrade security. I admit that
1133 * this doesn't capture everything.
1135 if (st
->st_pfs_group
!= NULL
)
1136 policy
|= POLICY_PFS
;
1137 if (st
->st_ah
.present
)
1139 policy
|= POLICY_AUTHENTICATE
;
1140 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1141 policy
|= POLICY_TUNNEL
;
1143 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1145 policy
|= POLICY_ENCRYPT
;
1146 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1147 policy
|= POLICY_TUNNEL
;
1149 if (st
->st_ipcomp
.present
)
1151 policy
|= POLICY_COMPRESS
;
1152 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1153 policy
|= POLICY_TUNNEL
;
1155 passert(HAS_IPSEC_POLICY(policy
));
1156 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1161 /* SKEYID for preshared keys.
1162 * See draft-ietf-ipsec-ike-01.txt 4.1
1165 skeyid_preshared(struct state
*st
)
1167 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1171 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1176 struct hmac_ctx ctx
;
1178 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, *pss
);
1179 hmac_update_chunk(&ctx
, st
->st_ni
);
1180 hmac_update_chunk(&ctx
, st
->st_nr
);
1181 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_preshared()", &ctx
);
1187 skeyid_digisig(struct state
*st
)
1189 struct hmac_ctx ctx
;
1192 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1193 * so we have to build a temporary concatentation.
1195 nir
.len
= st
->st_ni
.len
+ st
->st_nr
.len
;
1196 nir
.ptr
= alloc_bytes(nir
.len
, "Ni + Nr in skeyid_digisig");
1197 memcpy(nir
.ptr
, st
->st_ni
.ptr
, st
->st_ni
.len
);
1198 memcpy(nir
.ptr
+st
->st_ni
.len
, st
->st_nr
.ptr
, st
->st_nr
.len
);
1199 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, nir
);
1202 hmac_update_chunk(&ctx
, st
->st_shared
);
1203 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_digisig()", &ctx
);
1207 /* Generate the SKEYID_* and new IV
1208 * See draft-ietf-ipsec-ike-01.txt 4.1
1211 generate_skeyids_iv(struct state
*st
)
1213 /* Generate the SKEYID */
1214 switch (st
->st_oakley
.auth
)
1216 case OAKLEY_PRESHARED_KEY
:
1217 case XAUTHInitPreShared
:
1218 case XAUTHRespPreShared
:
1219 if (!skeyid_preshared(st
))
1223 case OAKLEY_RSA_SIG
:
1226 if (!skeyid_digisig(st
))
1230 case OAKLEY_DSS_SIG
:
1233 case OAKLEY_RSA_ENC
:
1234 case OAKLEY_RSA_ENC_REV
:
1235 case OAKLEY_ELGAMAL_ENC
:
1236 case OAKLEY_ELGAMAL_ENC_REV
:
1240 bad_case(st
->st_oakley
.auth
);
1243 /* generate SKEYID_* from SKEYID */
1245 struct hmac_ctx ctx
;
1247 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1250 hmac_update_chunk(&ctx
, st
->st_shared
);
1251 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1252 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1253 hmac_update(&ctx
, "\0", 1);
1254 hmac_final_chunk(st
->st_skeyid_d
, "st_skeyid_d in generate_skeyids_iv()", &ctx
);
1258 hmac_update_chunk(&ctx
, st
->st_skeyid_d
);
1259 hmac_update_chunk(&ctx
, st
->st_shared
);
1260 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1261 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1262 hmac_update(&ctx
, "\1", 1);
1263 hmac_final_chunk(st
->st_skeyid_a
, "st_skeyid_a in generate_skeyids_iv()", &ctx
);
1267 hmac_update_chunk(&ctx
, st
->st_skeyid_a
);
1268 hmac_update_chunk(&ctx
, st
->st_shared
);
1269 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1270 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1271 hmac_update(&ctx
, "\2", 1);
1272 hmac_final_chunk(st
->st_skeyid_e
, "st_skeyid_e in generate_skeyids_iv()", &ctx
);
1277 union hash_ctx hash_ctx
;
1278 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1280 st
->st_new_iv_len
= h
->hash_digest_size
;
1281 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1284 DBG_dump_chunk("DH_i:", st
->st_gi
);
1285 DBG_dump_chunk("DH_r:", st
->st_gr
);
1287 h
->hash_init(&hash_ctx
);
1288 h
->hash_update(&hash_ctx
, st
->st_gi
.ptr
, st
->st_gi
.len
);
1289 h
->hash_update(&hash_ctx
, st
->st_gr
.ptr
, st
->st_gr
.len
);
1290 h
->hash_final(st
->st_new_iv
, &hash_ctx
);
1293 /* Oakley Keying Material
1294 * Derived from Skeyid_e: if it is not big enough, generate more
1296 * See RFC 2409 "IKE" Appendix B
1299 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1300 const size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1301 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1302 u_char
*k
= st
->st_skeyid_e
.ptr
;
1304 if (keysize
> st
->st_skeyid_e
.len
)
1306 struct hmac_ctx ctx
;
1309 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_e
);
1310 hmac_update(&ctx
, "\0", 1);
1313 hmac_final(&keytemp
[i
], &ctx
);
1314 i
+= ctx
.hmac_digest_size
;
1318 hmac_update(&ctx
, &keytemp
[i
- ctx
.hmac_digest_size
], ctx
.hmac_digest_size
);
1322 clonereplacechunk(st
->st_enc_key
, k
, keysize
, "st_enc_key");
1326 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1327 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1328 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1329 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1330 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1331 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1335 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1336 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1337 * New Group Mode, or ISAKMP Informational Exchanges).
1338 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1339 * If hashus argument is TRUE, we're generating a hash for our end.
1340 * See RFC2409 IKE 5.
1342 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1343 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1344 * The extensive common logic is embodied in main_mode_hash_body().
1345 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1348 typedef void (*hash_update_t
)(union hash_ctx
*, const u_char
*, size_t) ;
1350 main_mode_hash_body(struct state
*st
1351 , bool hashi
/* Initiator? */
1352 , const pb_stream
*idpl
/* ID payload, as PBS */
1353 , union hash_ctx
*ctx
1354 , void (*hash_update_void
)(void *, const u_char
*input
, size_t))
1356 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1357 hash_update_t hash_update
=(hash_update_t
) hash_update_void
;
1358 #if 0 /* if desperate to debug hashing */
1359 # define hash_update(ctx, input, len) { \
1360 DBG_dump("hash input", input, len); \
1361 (hash_update)(ctx, input, len); \
1365 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1369 hash_update_chunk(ctx
, st
->st_gi
);
1370 hash_update_chunk(ctx
, st
->st_gr
);
1371 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1372 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1376 hash_update_chunk(ctx
, st
->st_gr
);
1377 hash_update_chunk(ctx
, st
->st_gi
);
1378 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1379 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1382 DBG(DBG_CRYPT
, DBG_log("hashing %lu bytes of SA"
1383 , (unsigned long) (st
->st_p1isa
.len
- sizeof(struct isakmp_generic
))));
1386 hash_update(ctx
, st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
)
1387 , st
->st_p1isa
.len
- sizeof(struct isakmp_generic
));
1389 /* Hash identification payload, without generic payload header.
1390 * We used to reconstruct ID Payload for this purpose, but now
1391 * we use the bytes as they appear on the wire to avoid
1392 * "spelling problems".
1395 , idpl
->start
+ sizeof(struct isakmp_generic
)
1396 , pbs_offset(idpl
) - sizeof(struct isakmp_generic
));
1398 # undef hash_update_chunk
1402 static size_t /* length of hash */
1403 main_mode_hash(struct state
*st
1404 , u_char
*hash_val
/* resulting bytes */
1405 , bool hashi
/* Initiator? */
1406 , const pb_stream
*idpl
) /* ID payload, as PBS; cur must be at end */
1408 struct hmac_ctx ctx
;
1410 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1411 main_mode_hash_body(st
, hashi
, idpl
, &ctx
.hash_ctx
, ctx
.h
->hash_update
);
1412 hmac_final(hash_val
, &ctx
);
1413 return ctx
.hmac_digest_size
;
1416 #if 0 /* only needed for DSS */
1418 main_mode_sha1(struct state
*st
1419 , u_char
*hash_val
/* resulting bytes */
1420 , size_t *hash_len
/* length of hash */
1421 , bool hashi
/* Initiator? */
1422 , const pb_stream
*idpl
) /* ID payload, as PBS */
1426 SHA1Init(&ctx
.ctx_sha1
);
1427 SHA1Update(&ctx
.ctx_sha1
, st
->st_skeyid
.ptr
, st
->st_skeyid
.len
);
1428 *hash_len
= SHA1_DIGEST_SIZE
;
1429 main_mode_hash_body(st
, hashi
, idpl
, &ctx
1430 , (void (*)(union hash_ctx
*, const u_char
*, unsigned int))&SHA1Update
);
1431 SHA1Final(hash_val
, &ctx
.ctx_sha1
);
1435 /* Create an RSA signature of a hash.
1436 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1437 * Use PKCS#1 version 1.5 encryption of hash (called
1438 * RSAES-PKCS1-V1_5) in PKCS#2.
1441 RSA_sign_hash(struct connection
*c
1442 , u_char sig_val
[RSA_MAX_OCTETS
]
1443 , const u_char
*hash_val
, size_t hash_len
)
1446 smartcard_t
*sc
= c
->spd
.this.sc
;
1448 if (sc
== NULL
) /* no smartcard */
1450 const struct RSA_private_key
*k
= get_RSA_private_key(c
);
1453 return 0; /* failure: no key to use */
1456 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1457 sign_hash(k
, hash_val
, hash_len
, sig_val
, sz
);
1459 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1461 lock_certs_and_keys("RSA_sign_hash");
1462 if (!scx_establish_context(sc
) || !scx_login(sc
))
1464 scx_release_context(sc
);
1465 unlock_certs_and_keys("RSA_sign_hash");
1469 sz
= scx_get_keylength(sc
);
1472 plog("failed to get keylength from smartcard");
1473 scx_release_context(sc
);
1474 unlock_certs_and_keys("RSA_sign_hash");
1478 DBG(DBG_CONTROL
| DBG_CRYPT
,
1479 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1480 , (int)sc
->slot
, sc
->id
)
1482 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1483 if (!pkcs11_keep_state
)
1484 scx_release_context(sc
);
1485 unlock_certs_and_keys("RSA_sign_hash");
1490 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1492 * As a side effect, on success, the public key is copied into the
1493 * state object to record the authenticator.
1495 * Can fail because wrong public key is used or because hash disagrees.
1496 * We distinguish because diagnostics should also.
1498 * The result is NULL if the Signature checked out.
1499 * Otherwise, the first character of the result indicates
1500 * how far along failure occurred. A greater character signifies
1504 * 0 reserved for caller
1505 * 1 SIG length doesn't match key length -- wrong key
1506 * 2-8 malformed ECB after decryption -- probably wrong key
1507 * 9 decrypted hash != computed hash -- probably correct key
1509 * Although the math should be the same for generating and checking signatures,
1510 * it is not: the knowledge of the private key allows more efficient (i.e.
1511 * different) computation for encryption.
1514 try_RSA_signature(const u_char hash_val
[MAX_DIGEST_LEN
], size_t hash_len
1515 , const pb_stream
*sig_pbs
, pubkey_t
*kr
1518 const u_char
*sig_val
= sig_pbs
->cur
;
1519 size_t sig_len
= pbs_left(sig_pbs
);
1520 u_char s
[RSA_MAX_OCTETS
]; /* for decrypted sig_val */
1521 u_char
*hash_in_s
= &s
[sig_len
- hash_len
];
1522 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1524 /* decrypt the signature -- reversing RSA_sign_hash */
1525 if (sig_len
!= k
->k
)
1527 /* XXX notification: INVALID_KEY_INFORMATION */
1528 return "1" "SIG length does not match public key length";
1531 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1536 n_to_mpz(c
, sig_val
, sig_len
);
1537 mpz_powm(c
, c
, &k
->e
, &k
->n
);
1539 temp_s
= mpz_to_n(c
, sig_len
); /* back to octets */
1540 memcpy(s
, temp_s
.ptr
, sig_len
);
1545 /* sanity check on signature: see if it matches
1546 * PKCS#1 v1.5 8.1 encryption-block formatting
1552 ugh
= "2" "no leading 00";
1553 else if (hash_in_s
[-1] != 0x00)
1554 ugh
= "3" "00 separator not present";
1555 else if (s
[1] == 0x01)
1559 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1563 ugh
= "4" "invalid Padding String";
1568 else if (s
[1] == 0x02)
1572 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1576 ugh
= "5" "invalid Padding String";
1582 ugh
= "6" "Block Type not 01 or 02";
1586 /* note: it might be a good idea to make sure that
1587 * an observer cannot tell what kind of failure happened.
1588 * I don't know what this means in practice.
1590 /* We probably selected the wrong public key for peer:
1591 * SIG Payload decrypted into malformed ECB
1593 /* XXX notification: INVALID_KEY_INFORMATION */
1598 /* We have the decoded hash: see if it matches. */
1599 if (memcmp(hash_val
, hash_in_s
, hash_len
) != 0)
1601 /* good: header, hash, signature, and other payloads well-formed
1602 * good: we could find an RSA Sig key for the peer.
1603 * bad: hash doesn't match
1604 * Guess: sides disagree about key to be used.
1606 DBG_cond_dump(DBG_CRYPT
, "decrypted SIG", s
, sig_len
);
1607 DBG_cond_dump(DBG_CRYPT
, "computed HASH", hash_val
, hash_len
);
1608 /* XXX notification: INVALID_HASH_INFORMATION */
1609 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1612 /* Success: copy successful key into state.
1613 * There might be an old one if we previously aborted this
1616 unreference_key(&st
->st_peer_pubkey
);
1617 st
->st_peer_pubkey
= reference_key(kr
);
1619 return NULL
; /* happy happy */
1622 /* Check signature against all RSA public keys we can find.
1623 * If we need keys from DNS KEY records, and they haven't been fetched,
1624 * return STF_SUSPEND to ask for asynch DNS lookup.
1626 * Note: parameter keys_from_dns contains results of DNS lookup for key
1627 * or is NULL indicating lookup not yet tried.
1629 * take_a_crack is a helper function. Mostly forensic.
1630 * If only we had coroutines.
1633 /* RSA_check_signature's args that take_a_crack needs */
1635 const u_char
*hash_val
;
1637 const pb_stream
*sig_pbs
;
1639 /* state carried between calls */
1640 err_t best_ugh
; /* most successful failure */
1641 int tried_cnt
; /* number of keys tried */
1642 char tried
[50]; /* keyids of tried public keys */
1643 char *tn
; /* roof of tried[] */
1647 take_a_crack(struct tac_state
*s
1649 , const char *story USED_BY_DEBUG
)
1651 err_t ugh
= try_RSA_signature(s
->hash_val
, s
->hash_len
, s
->sig_pbs
1653 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1658 DBG(DBG_CRYPT
| DBG_CONTROL
1659 , DBG_log("an RSA Sig check passed with *%s [%s]"
1660 , k
->keyid
, story
));
1666 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1667 , ugh
+ 1, k
->keyid
, story
));
1668 if (s
->best_ugh
== NULL
|| s
->best_ugh
[0] < ugh
[0])
1671 && s
->tn
- s
->tried
+ KEYID_BUF
+ 2 < (ptrdiff_t)sizeof(s
->tried
))
1673 strcpy(s
->tn
, " *");
1674 strcpy(s
->tn
+ 2, k
->keyid
);
1675 s
->tn
+= strlen(s
->tn
);
1682 RSA_check_signature(const struct id
* peer
1684 , const u_char hash_val
[MAX_DIGEST_LEN
]
1686 , const pb_stream
*sig_pbs
1688 , const pubkey_list_t
*keys_from_dns
1689 #endif /* USE_KEYRR */
1690 , const struct gw_info
*gateways_from_dns
1693 const struct connection
*c
= st
->st_connection
;
1695 err_t dns_ugh
= NULL
;
1698 s
.hash_val
= hash_val
;
1699 s
.hash_len
= hash_len
;
1700 s
.sig_pbs
= sig_pbs
;
1706 /* try all gateway records hung off c */
1707 if (c
->policy
& POLICY_OPPO
)
1711 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1713 /* only consider entries that have a key and are for our peer */
1714 if (gw
->gw_key_present
1715 && same_id(&gw
->gw_id
, &c
->spd
.that
.id
)
1716 && take_a_crack(&s
, gw
->key
, "key saved from DNS TXT"))
1721 /* try all appropriate Public keys */
1723 pubkey_list_t
*p
, **pp
;
1727 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1729 pubkey_t
*key
= p
->key
;
1731 if (key
->alg
== PUBKEY_ALG_RSA
&& same_id(peer
, &key
->id
))
1733 time_t now
= time(NULL
);
1735 /* check if found public key has expired */
1736 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1738 loglog(RC_LOG_SERIOUS
,
1739 "cached RSA public key has expired and has been deleted");
1740 *pp
= free_public_keyentry(p
);
1741 continue; /* continue with next public key */
1744 if (take_a_crack(&s
, key
, "preloaded key"))
1751 /* if no key was found (evidenced by best_ugh == NULL)
1752 * and that side of connection is key_from_DNS_on_demand
1753 * then go search DNS for keys for peer.
1755 if (s
.best_ugh
== NULL
&& c
->spd
.that
.key_from_DNS_on_demand
)
1757 if (gateways_from_dns
!= NULL
)
1760 const struct gw_info
*gwp
;
1762 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1763 if (gwp
->gw_key_present
1764 && take_a_crack(&s
, gwp
->key
, "key from DNS TXT"))
1768 else if (keys_from_dns
!= NULL
)
1771 const pubkey_list_t
*kr
;
1773 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1774 if (kr
->key
->alg
== PUBKEY_ALG_RSA
1775 && take_a_crack(&s
, kr
->key
, "key from DNS KEY"))
1778 #endif /* USE_KEYRR */
1781 /* nothing yet: ask for asynch DNS lookup */
1786 /* no acceptable key was found: diagnose */
1788 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1790 (void) idtoa(peer
, id_buf
, sizeof(id_buf
));
1792 if (s
.best_ugh
== NULL
)
1794 if (dns_ugh
== NULL
)
1795 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1798 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1799 "; DNS search for KEY failed (%s)"
1802 /* ??? is this the best code there is? */
1803 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1806 if (s
.best_ugh
[0] == '9')
1808 loglog(RC_LOG_SERIOUS
, "%s", s
.best_ugh
+ 1);
1809 /* XXX Could send notification back */
1810 return STF_FAIL
+ INVALID_HASH_INFORMATION
;
1814 if (s
.tried_cnt
== 1)
1816 loglog(RC_LOG_SERIOUS
1817 , "Signature check (on %s) failed (wrong key?); tried%s"
1820 DBG_log("public key for %s failed:"
1821 " decrypted SIG payload into a malformed ECB (%s)"
1822 , id_buf
, s
.best_ugh
+ 1));
1826 loglog(RC_LOG_SERIOUS
1827 , "Signature check (on %s) failed:"
1828 " tried%s keys but none worked."
1831 DBG_log("all %d public keys for %s failed:"
1832 " best decrypted SIG payload into a malformed ECB (%s)"
1833 , s
.tried_cnt
, id_buf
, s
.best_ugh
+ 1));
1835 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1840 static notification_t
1841 accept_nonce(struct msg_digest
*md
, chunk_t
*dest
, const char *name
)
1843 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1844 size_t len
= pbs_left(nonce_pbs
);
1846 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1848 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1849 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1850 return PAYLOAD_MALFORMED
; /* ??? */
1852 clonereplacechunk(*dest
, nonce_pbs
->cur
, len
, "nonce");
1853 return NOTHING_WRONG
;
1856 /* encrypt message, sans fixed part of header
1857 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1858 * The theory is that there will be no "backing out", so we commit to IV.
1859 * We also close the pbs.
1862 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1864 const struct encrypt_desc
*e
= st
->st_oakley
.encrypter
;
1865 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1866 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1868 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1870 /* Pad up to multiple of encryption blocksize.
1871 * See the description associated with the definition of
1872 * struct isakmp_hdr in packet.h.
1875 size_t padding
= pad_up(enc_len
, e
->enc_blocksize
);
1879 if (!out_zero(padding
, pbs
, "encryption padding"))
1885 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1887 /* e->crypt(TRUE, enc_start, enc_len, st); */
1888 crypto_cbc_encrypt(e
, TRUE
, enc_start
, enc_len
, st
);
1891 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1896 /* Compute HASH(1), HASH(2) of Quick Mode.
1897 * HASH(1) is part of Quick I1 message.
1898 * HASH(2) is part of Quick R1 message.
1899 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1900 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1903 quick_mode_hash12(u_char
*dest
, const u_char
*start
, const u_char
*roof
1904 , const struct state
*st
, const msgid_t
*msgid
, bool hash2
)
1906 struct hmac_ctx ctx
;
1908 #if 0 /* if desperate to debug hashing */
1909 # define hmac_update(ctx, ptr, len) { \
1910 DBG_dump("hash input", (ptr), (len)); \
1911 (hmac_update)((ctx), (ptr), (len)); \
1913 DBG_dump("hash key", st
->st_skeyid_a
.ptr
, st
->st_skeyid_a
.len
);
1915 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1916 hmac_update(&ctx
, (const void *) msgid
, sizeof(msgid_t
));
1918 hmac_update_chunk(&ctx
, st
->st_ni
); /* include Ni_b in the hash */
1919 hmac_update(&ctx
, start
, roof
-start
);
1920 hmac_final(dest
, &ctx
);
1923 DBG_log("HASH(%d) computed:", hash2
+ 1);
1924 DBG_dump("", dest
, ctx
.hmac_digest_size
));
1925 return ctx
.hmac_digest_size
;
1929 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1930 * Used by: quick_inR1_outI2, quick_inI2
1931 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1932 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1933 * Message ID and Nonces. This is a mistake.
1936 quick_mode_hash3(u_char
*dest
, struct state
*st
)
1938 struct hmac_ctx ctx
;
1940 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1941 hmac_update(&ctx
, "\0", 1);
1942 hmac_update(&ctx
, (u_char
*) &st
->st_msgid
, sizeof(st
->st_msgid
));
1943 hmac_update_chunk(&ctx
, st
->st_ni
);
1944 hmac_update_chunk(&ctx
, st
->st_nr
);
1945 hmac_final(dest
, &ctx
);
1946 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, ctx
.hmac_digest_size
);
1947 return ctx
.hmac_digest_size
;
1950 /* Compute Phase 2 IV.
1951 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1954 init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1956 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1959 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:"
1960 , st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1962 st
->st_new_iv_len
= h
->hash_digest_size
;
1963 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1966 h
->hash_update(&ctx
, st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1967 passert(*msgid
!= 0);
1968 h
->hash_update(&ctx
, (const u_char
*)msgid
, sizeof(*msgid
));
1969 h
->hash_final(st
->st_new_iv
, &ctx
);
1971 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:"
1972 , st
->st_new_iv
, st
->st_new_iv_len
);
1975 /* Initiate quick mode.
1976 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1977 * (see RFC 2409 "IKE" 5.5)
1978 * Note: this is not called from demux.c
1982 emit_subnet_id(ip_subnet
*net
1983 , u_int8_t np
, u_int8_t protoid
, u_int16_t port
, pb_stream
*outs
)
1985 struct isakmp_ipsec_id id
;
1988 const unsigned char *tbp
;
1992 id
.isaiid_idtype
= subnetishost(net
)
1993 ?
aftoinfo(subnettypeof(net
))->id_addr
1994 : aftoinfo(subnettypeof(net
))->id_subnet
;
1995 id
.isaiid_protoid
= protoid
;
1996 id
.isaiid_port
= port
;
1998 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
2001 networkof(net
, &ta
);
2002 tal
= addrbytesptr(&ta
, &tbp
);
2003 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
2006 if (!subnetishost(net
))
2009 tal
= addrbytesptr(&ta
, &tbp
);
2010 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
2014 close_output_pbs(&id_pbs
);
2019 quick_outI1(int whack_sock
2020 , struct state
*isakmp_sa
2021 , struct connection
*c
2024 , so_serial_t replacing
)
2026 struct state
*st
= duplicate_state(isakmp_sa
);
2027 pb_stream reply
; /* not really a reply */
2029 u_char
/* set by START_HASH_PAYLOAD: */
2030 *r_hashval
, /* where in reply to jam hash value */
2031 *r_hash_start
; /* start of what is to be hashed */
2032 bool has_client
= c
->spd
.this.has_client
|| c
->spd
.that
.has_client
||
2033 c
->spd
.this.protocol
|| c
->spd
.that
.protocol
||
2034 c
->spd
.this.port
|| c
->spd
.that
.port
;
2036 bool send_natoa
= FALSE
;
2037 u_int8_t np
= ISAKMP_NEXT_NONE
;
2039 st
->st_whack_sock
= whack_sock
;
2040 st
->st_connection
= c
;
2041 set_cur_state(st
); /* we must reset before exit */
2042 st
->st_policy
= policy
;
2045 st
->st_myuserprotoid
= c
->spd
.this.protocol
;
2046 st
->st_peeruserprotoid
= c
->spd
.that
.protocol
;
2047 st
->st_myuserport
= c
->spd
.this.port
;
2048 st
->st_peeruserport
= c
->spd
.that
.port
;
2050 st
->st_msgid
= generate_msgid(isakmp_sa
);
2051 st
->st_state
= STATE_QUICK_I1
;
2053 insert_state(st
); /* needs cookies, connection, and msgid */
2055 if (replacing
== SOS_NOBODY
)
2056 plog("initiating Quick Mode %s {using isakmp#%lu}"
2057 , prettypolicy(policy
)
2058 , isakmp_sa
->st_serialno
);
2060 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2061 , prettypolicy(policy
)
2063 , isakmp_sa
->st_serialno
);
2065 if (isakmp_sa
->nat_traversal
& NAT_T_DETECTED
)
2067 /* Duplicate nat_traversal status in new state */
2068 st
->nat_traversal
= isakmp_sa
->nat_traversal
;
2070 if (isakmp_sa
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
))
2073 nat_traversal_change_port_lookup(NULL
, st
);
2076 st
->nat_traversal
= 0;
2078 /* are we going to send a NAT-OA payload? */
2079 if ((st
->nat_traversal
& NAT_T_WITH_NATOA
)
2080 && !(st
->st_policy
& POLICY_TUNNEL
)
2081 && (st
->nat_traversal
& LELEM(NAT_TRAVERSAL_NAT_BHND_ME
)))
2084 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
2085 ISAKMP_NEXT_NATOA_RFC
: ISAKMP_NEXT_NATOA_DRAFTS
;
2089 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
2093 struct isakmp_hdr hdr
;
2095 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
2096 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
2097 hdr
.isa_xchg
= ISAKMP_XCHG_QUICK
;
2098 hdr
.isa_msgid
= st
->st_msgid
;
2099 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
2100 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
2101 memcpy(hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
2102 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
2105 return STF_INTERNAL_ERROR
;
2109 /* HASH(1) -- create and note space to be filled later */
2110 START_HASH_PAYLOAD(rbody
, ISAKMP_NEXT_SA
);
2115 * See if pfs_group has been specified for this conn,
2116 * if not, fallback to old use-same-as-P1 behaviour
2119 if (st
->st_connection
)
2120 st
->st_pfs_group
= ike_alg_pfsgroup(st
->st_connection
, policy
);
2121 if (!st
->st_pfs_group
)
2123 /* If PFS specified, use the same group as during Phase 1:
2124 * since no negotiation is possible, we pick one that is
2125 * very likely supported.
2127 st
->st_pfs_group
= policy
& POLICY_PFS? isakmp_sa
->st_oakley
.group
: NULL
;
2129 /* Emit SA payload based on a subset of the policy bits.
2130 * POLICY_COMPRESS is considered iff we can do IPcomp.
2133 lset_t pm
= POLICY_ENCRYPT
| POLICY_AUTHENTICATE
;
2136 pm
|= POLICY_COMPRESS
;
2139 , &ipsec_sadb
[(st
->st_policy
& pm
) >> POLICY_IPSEC_SHIFT
]
2140 , st
, FALSE
, ISAKMP_NEXT_NONCE
))
2143 return STF_INTERNAL_ERROR
;
2148 if (!build_and_ship_nonce(&st
->st_ni
, &rbody
2149 , policy
& POLICY_PFS? ISAKMP_NEXT_KE
: has_client? ISAKMP_NEXT_ID
: np
2153 return STF_INTERNAL_ERROR
;
2156 /* [ KE ] out (for PFS) */
2158 if (st
->st_pfs_group
!= NULL
)
2160 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_pfs_group
2161 , &rbody
, has_client? ISAKMP_NEXT_ID
: np
))
2164 return STF_INTERNAL_ERROR
;
2168 /* [ IDci, IDcr ] out */
2171 /* IDci (we are initiator), then IDcr (peer is responder) */
2172 if (!emit_subnet_id(&c
->spd
.this.client
2173 , ISAKMP_NEXT_ID
, st
->st_myuserprotoid
, st
->st_myuserport
, &rbody
)
2174 || !emit_subnet_id(&c
->spd
.that
.client
2175 , np
, st
->st_peeruserprotoid
, st
->st_peeruserport
, &rbody
))
2178 return STF_INTERNAL_ERROR
;
2182 /* Send NAT-OA if our address is NATed */
2185 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE
, &rbody
, st
))
2188 return STF_INTERNAL_ERROR
;
2192 /* finish computing HASH(1), inserting it in output */
2193 (void) quick_mode_hash12(r_hashval
, r_hash_start
, rbody
.cur
2194 , st
, &st
->st_msgid
, FALSE
);
2196 /* encrypt message, except for fixed part of header */
2198 init_phase2_iv(isakmp_sa
, &st
->st_msgid
);
2199 st
->st_new_iv_len
= isakmp_sa
->st_new_iv_len
;
2200 memcpy(st
->st_new_iv
, isakmp_sa
->st_new_iv
, st
->st_new_iv_len
);
2202 if (!encrypt_message(&rbody
, st
))
2205 return STF_INTERNAL_ERROR
;
2208 /* save packet, now that we know its size */
2209 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
2210 , "reply packet from quick_outI1");
2212 /* send the packet */
2214 send_packet(st
, "quick_outI1");
2217 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
2219 if (replacing
== SOS_NOBODY
)
2220 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2222 , enum_name(&state_names
, st
->st_state
));
2224 whack_log(RC_NEW_STATE
+ STATE_QUICK_I1
2225 , "%s: initiate to replace #%lu"
2226 , enum_name(&state_names
, st
->st_state
)
2234 * Decode the CERT payload of Phase 1.
2237 decode_cert(struct msg_digest
*md
)
2239 struct payload_digest
*p
;
2241 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2243 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2246 blob
.ptr
= p
->pbs
.cur
;
2247 blob
.len
= pbs_left(&p
->pbs
);
2248 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2250 x509cert_t cert
= empty_x509cert
;
2251 if (parse_x509cert(blob
, 0, &cert
))
2253 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2256 DBG_log("Public key validated")
2258 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2262 plog("X.509 certificate rejected");
2264 free_generalNames(cert
.subjectAltName
, FALSE
);
2265 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2268 plog("Syntax error in X.509 certificate");
2270 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2272 x509cert_t
*cert
= NULL
;
2274 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2275 store_x509certs(&cert
, strict_crl_policy
);
2277 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2281 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2282 enum_show(&cert_type_names
, cert
->isacert_type
));
2283 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2289 * Decode the CR payload of Phase 1.
2292 decode_cr(struct msg_digest
*md
, struct connection
*c
)
2294 struct payload_digest
*p
;
2296 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2298 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2301 ca_name
.len
= pbs_left(&p
->pbs
);
2302 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2304 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2306 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2310 if (ca_name
.len
> 0)
2314 if (!is_asn1(ca_name
))
2317 gn
= alloc_thing(generalName_t
, "generalName");
2318 clonetochunk(ca_name
, ca_name
.ptr
,ca_name
.len
, "ca name");
2319 gn
->kind
= GN_DIRECTORY_NAME
;
2321 gn
->next
= c
->requested_ca
;
2322 c
->requested_ca
= gn
;
2324 c
->got_certrequest
= TRUE
;
2326 DBG(DBG_PARSING
| DBG_CONTROL
,
2327 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2328 DBG_log("requested CA: '%s'", buf
);
2332 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2333 enum_show(&cert_type_names
, cr
->isacr_type
));
2337 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2338 * Note: we may change connections as a result.
2339 * We must be called before SIG or HASH are decoded since we
2340 * may change the peer's RSA key or ID.
2343 decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2345 struct state
*const st
= md
->st
;
2346 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2347 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2348 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2350 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2351 * It talks about the protocol ID and Port fields of the ID
2352 * Payload, but they don't exist as such in Phase 1.
2353 * We use more appropriate names.
2354 * isaid_doi_specific_a is in place of Protocol ID.
2355 * isaid_doi_specific_b is in place of Port.
2356 * Besides, there is no good reason for allowing these to be
2357 * other than 0 in Phase 1.
2359 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2360 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2361 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2363 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2364 "accepted with port_floating NAT-T",
2365 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2367 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2368 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2370 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2372 , IPPROTO_UDP
, IKE_UDP_PORT
2373 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2377 peer
->kind
= id
->isaid_idtype
;
2383 /* failure mode for initaddr is probably inappropriate address length */
2385 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2386 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2391 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2392 , enum_show(&ident_names
, peer
->kind
), ugh
);
2393 /* XXX Could send notification back */
2400 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2402 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2407 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2409 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2410 , enum_show(&ident_names
, peer
->kind
));
2414 /* ??? ought to do some more sanity check, but what? */
2416 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2420 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2422 DBG_dump_chunk("KEY ID:", peer
->name
));
2425 case ID_DER_ASN1_DN
:
2426 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2428 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2432 /* XXX Could send notification back */
2433 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2434 , enum_show(&ident_names
, peer
->kind
));
2441 idtoa(peer
, buf
, sizeof(buf
));
2442 plog("Peer ID is %s: '%s'",
2443 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2446 /* check for certificates */
2451 /* Now that we've decoded the ID payload, let's see if we
2452 * need to switch connections.
2453 * We must not switch horses if we initiated:
2454 * - if the initiation was explicit, we'd be ignoring user's intent
2455 * - if opportunistic, we'll lose our HOLD info
2458 switch_connection(struct msg_digest
*md
, struct id
*peer
, bool initiator
)
2460 struct state
*const st
= md
->st
;
2461 struct connection
*c
= st
->st_connection
;
2463 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2464 ? st
->st_peer_pubkey
->issuer
: empty_chunk
;
2469 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2470 DBG_log("peer CA: '%s'", buf
);
2477 if (!same_id(&c
->spd
.that
.id
, peer
))
2479 char expect
[BUF_LEN
]
2482 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2483 idtoa(peer
, found
, sizeof(found
));
2484 loglog(RC_LOG_SERIOUS
2485 , "we require peer to have ID '%s', but peer declares '%s'"
2493 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.that
.ca
, "%none");
2494 DBG_log("required CA: '%s'", buf
);
2497 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2499 loglog(RC_LOG_SERIOUS
2500 , "we don't accept the peer's CA");
2506 struct connection
*r
;
2508 /* check for certificate requests */
2511 r
= refine_host_connection(st
, peer
, peer_ca
);
2513 /* delete the collected certificate requests */
2514 free_generalNames(c
->requested_ca
, TRUE
);
2515 c
->requested_ca
= NULL
;
2521 idtoa(peer
, buf
, sizeof(buf
));
2522 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2529 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2530 DBG_log("offered CA: '%s'", buf
);
2535 /* apparently, r is an improvement on c -- replace */
2538 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2539 if (r
->kind
== CK_TEMPLATE
)
2541 /* instantiate it, filling in peer's ID */
2542 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2543 , c
->spd
.that
.host_port
, NULL
, peer
);
2546 /* copy certificate request info */
2547 r
->got_certrequest
= c
->got_certrequest
;
2549 st
->st_connection
= r
; /* kill reference to c */
2550 set_cur_connection(r
);
2551 connection_discard(c
);
2553 else if (c
->spd
.that
.has_id_wildcards
)
2555 free_id_content(&c
->spd
.that
.id
);
2556 c
->spd
.that
.id
= *peer
;
2557 c
->spd
.that
.has_id_wildcards
= FALSE
;
2558 unshare_id_content(&c
->spd
.that
.id
);
2564 /* Decode the variable part of an ID packet (during Quick Mode).
2565 * This is designed for packets that identify clients, not peers.
2566 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2567 * (1) it is wrong and (2) we use this value for inband signalling.
2570 decode_net_id(struct isakmp_ipsec_id
*id
2573 , const char *which
)
2575 const struct af_info
*afi
= NULL
;
2577 /* Note: the following may be a pointer into static memory
2578 * that may be recycled, but only if the type is not known.
2579 * That case is disposed of very early -- in the first switch.
2581 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2583 switch (id
->isaiid_idtype
)
2586 case ID_IPV4_ADDR_SUBNET
:
2587 case ID_IPV4_ADDR_RANGE
:
2588 afi
= &af_inet4_info
;
2591 case ID_IPV6_ADDR_SUBNET
:
2592 case ID_IPV6_ADDR_RANGE
:
2593 afi
= &af_inet6_info
;
2598 /* XXX support more */
2599 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2601 /* XXX Could send notification back */
2605 switch (id
->isaiid_idtype
)
2610 ip_address temp_address
;
2613 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2617 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2618 , which
, idtypename
, ugh
);
2619 /* XXX Could send notification back */
2622 if (isanyaddr(&temp_address
))
2624 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2625 , which
, idtypename
, ip_str(&temp_address
));
2626 /* XXX Could send notification back */
2629 happy(addrtosubnet(&temp_address
, net
));
2630 DBG(DBG_PARSING
| DBG_CONTROL
2631 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2635 case ID_IPV4_ADDR_SUBNET
:
2636 case ID_IPV6_ADDR_SUBNET
:
2638 ip_address temp_address
, temp_mask
;
2641 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2643 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2644 , which
, idtypename
);
2645 /* XXX Could send notification back */
2648 ugh
= initaddr(id_pbs
->cur
2649 , afi
->ia_sz
, afi
->af
, &temp_address
);
2651 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2652 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2654 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2656 if (ugh
== NULL
&& subnetisnone(net
))
2657 ugh
= "contains only anyaddr";
2660 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2661 , which
, idtypename
, ugh
);
2662 /* XXX Could send notification back */
2665 DBG(DBG_PARSING
| DBG_CONTROL
,
2667 char temp_buff
[SUBNETTOT_BUF
];
2669 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2670 DBG_log("%s is subnet %s", which
, temp_buff
);
2675 case ID_IPV4_ADDR_RANGE
:
2676 case ID_IPV6_ADDR_RANGE
:
2678 ip_address temp_address_from
, temp_address_to
;
2681 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2683 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2684 , which
, idtypename
);
2685 /* XXX Could send notification back */
2688 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2690 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2691 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2694 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2695 , which
, idtypename
, ugh
);
2696 /* XXX Could send notification back */
2700 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2701 if (ugh
== NULL
&& subnetisnone(net
))
2702 ugh
= "contains only anyaddr";
2705 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2707 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2708 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2709 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2710 " %s - %s unacceptable: %s"
2711 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2714 DBG(DBG_PARSING
| DBG_CONTROL
,
2716 char temp_buff
[SUBNETTOT_BUF
];
2718 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2719 DBG_log("%s is subnet %s (received as range)"
2720 , which
, temp_buff
);
2726 /* set the port selector */
2727 setportof(htons(id
->isaiid_port
), &net
->addr
);
2729 DBG(DBG_PARSING
| DBG_CONTROL
,
2730 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2736 /* like decode, but checks that what is received matches what was sent */
2739 check_net_id(struct isakmp_ipsec_id
*id
2744 , const char *which
)
2748 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2751 if (!samesubnet(net
, &net_temp
)
2752 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2754 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2761 * look for the existence of a non-expiring preloaded public key
2764 has_preloaded_public_key(struct state
*st
)
2766 struct connection
*c
= st
->st_connection
;
2768 /* do not consider rw connections since
2769 * the peer's identity must be known
2771 if (c
->kind
== CK_PERMANENT
)
2775 /* look for a matching RSA public key */
2776 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2778 pubkey_t
*key
= p
->key
;
2780 if (key
->alg
== PUBKEY_ALG_RSA
&&
2781 same_id(&c
->spd
.that
.id
, &key
->id
) &&
2782 key
->until_time
== UNDEFINED_TIME
)
2784 /* found a preloaded public key */
2793 * Produce the new key material of Quick Mode.
2794 * RFC 2409 "IKE" section 5.5
2795 * specifies how this is to be done.
2798 compute_proto_keymat(struct state
*st
2800 , struct ipsec_proto_info
*pi
)
2802 size_t needed_len
= 0; /* bytes of keying material needed */
2804 /* Add up the requirements for keying material
2805 * (It probably doesn't matter if we produce too much!)
2809 case PROTO_IPSEC_ESP
:
2810 switch (pi
->attrs
.transid
)
2816 needed_len
= DES_CBC_BLOCK_SIZE
;
2819 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2822 #ifndef NO_KERNEL_ALG
2823 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2824 /* XXX: check key_len "coupling with kernel.c's */
2825 if (pi
->attrs
.key_len
) {
2826 needed_len
=pi
->attrs
.key_len
/8;
2827 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2828 "key_len=%d from peer",
2834 bad_case(pi
->attrs
.transid
);
2837 #ifndef NO_KERNEL_ALG
2838 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2839 "needed_len (after ESP enc)=%d",
2841 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2842 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2845 switch (pi
->attrs
.auth
)
2847 case AUTH_ALGORITHM_NONE
:
2849 case AUTH_ALGORITHM_HMAC_MD5
:
2850 needed_len
+= HMAC_MD5_KEY_LEN
;
2852 case AUTH_ALGORITHM_HMAC_SHA1
:
2853 needed_len
+= HMAC_SHA1_KEY_LEN
;
2855 case AUTH_ALGORITHM_DES_MAC
:
2857 bad_case(pi
->attrs
.auth
);
2859 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2860 "needed_len (after ESP auth)=%d",
2864 case PROTO_IPSEC_AH
:
2865 switch (pi
->attrs
.transid
)
2868 needed_len
= HMAC_MD5_KEY_LEN
;
2871 needed_len
= HMAC_SHA1_KEY_LEN
;
2874 bad_case(pi
->attrs
.transid
);
2882 pi
->keymat_len
= needed_len
;
2884 /* Allocate space for the keying material.
2885 * Although only needed_len bytes are desired, we
2886 * must round up to a multiple of ctx.hmac_digest_size
2887 * so that our buffer isn't overrun.
2890 struct hmac_ctx ctx_me
, ctx_peer
;
2891 size_t needed_space
; /* space needed for keying material (rounded up) */
2894 hmac_init_chunk(&ctx_me
, st
->st_oakley
.hasher
, st
->st_skeyid_d
);
2895 ctx_peer
= ctx_me
; /* duplicate initial conditions */
2897 needed_space
= needed_len
+ pad_up(needed_len
, ctx_me
.hmac_digest_size
);
2898 replace(pi
->our_keymat
, alloc_bytes(needed_space
, "keymat in compute_keymat()"));
2899 replace(pi
->peer_keymat
, alloc_bytes(needed_space
, "peer_keymat in quick_inI1_outR1()"));
2903 if (st
->st_shared
.ptr
!= NULL
)
2905 /* PFS: include the g^xy */
2906 hmac_update_chunk(&ctx_me
, st
->st_shared
);
2907 hmac_update_chunk(&ctx_peer
, st
->st_shared
);
2909 hmac_update(&ctx_me
, &protoid
, sizeof(protoid
));
2910 hmac_update(&ctx_peer
, &protoid
, sizeof(protoid
));
2912 hmac_update(&ctx_me
, (u_char
*)&pi
->our_spi
, sizeof(pi
->our_spi
));
2913 hmac_update(&ctx_peer
, (u_char
*)&pi
->attrs
.spi
, sizeof(pi
->attrs
.spi
));
2915 hmac_update_chunk(&ctx_me
, st
->st_ni
);
2916 hmac_update_chunk(&ctx_peer
, st
->st_ni
);
2918 hmac_update_chunk(&ctx_me
, st
->st_nr
);
2919 hmac_update_chunk(&ctx_peer
, st
->st_nr
);
2921 hmac_final(pi
->our_keymat
+ i
, &ctx_me
);
2922 hmac_final(pi
->peer_keymat
+ i
, &ctx_peer
);
2924 i
+= ctx_me
.hmac_digest_size
;
2925 if (i
>= needed_space
)
2928 /* more keying material needed: prepare to go around again */
2930 hmac_reinit(&ctx_me
);
2931 hmac_reinit(&ctx_peer
);
2933 hmac_update(&ctx_me
, pi
->our_keymat
+ i
- ctx_me
.hmac_digest_size
2934 , ctx_me
.hmac_digest_size
);
2935 hmac_update(&ctx_peer
, pi
->peer_keymat
+ i
- ctx_peer
.hmac_digest_size
2936 , ctx_peer
.hmac_digest_size
);
2941 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2942 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2946 compute_keymats(struct state
*st
)
2948 if (st
->st_ah
.present
)
2949 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2950 if (st
->st_esp
.present
)
2951 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2954 /* State Transition Functions.
2956 * The definition of state_microcode_table in demux.c is a good
2957 * overview of these routines.
2959 * - Called from process_packet; result handled by complete_state_transition
2960 * - struct state_microcode member "processor" points to these
2961 * - these routine definitionss are in state order
2962 * - these routines must be restartable from any point of error return:
2963 * beware of memory allocated before any error.
2964 * - output HDR is usually emitted by process_packet (if state_microcode
2965 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2967 * The transition functions' functions include:
2968 * - process and judge payloads
2969 * - update st_iv (result of decryption is in st_new_iv)
2970 * - build reply packet
2973 /* Handle a Main Mode Oakley first packet (responder side).
2977 main_inI1_outR1(struct msg_digest
*md
)
2979 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2981 struct connection
*c
;
2982 struct isakmp_proposal proposal
;
2983 pb_stream proposal_pbs
;
2985 u_int32_t ipsecdoisit
;
2986 lset_t policy
= LEMPTY
;
2987 int vids_to_send
= 0;
2989 /* We preparse the peer's proposal in order to determine
2990 * the requested authentication policy (RSA or PSK)
2992 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2993 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2995 backup_pbs(&proposal_pbs
);
2996 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2997 , proposal
.isap_notrans
, &policy
));
2998 restore_pbs(&proposal_pbs
);
3000 /* We are only considering candidate connections that match
3001 * the requested authentication policy (RSA or PSK)
3003 c
= find_host_connection(&md
->iface
->addr
, pluto_port
3004 , &md
->sender
, md
->sender_port
, policy
);
3006 if (c
== NULL
&& md
->iface
->ike_float
)
3008 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
3009 , &md
->sender
, md
->sender_port
, policy
);
3014 /* See if a wildcarded connection can be found.
3015 * We cannot pick the right connection, so we're making a guess.
3016 * All Road Warrior connections are fair game:
3017 * we pick the first we come across (if any).
3018 * If we don't find any, we pick the first opportunistic
3019 * with the smallest subnet that includes the peer.
3020 * There is, of course, no necessary relationship between
3021 * an Initiator's address and that of its client,
3022 * but Food Groups kind of assumes one.
3025 struct connection
*d
;
3027 d
= find_host_connection(&md
->iface
->addr
3028 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
3030 for (; d
!= NULL
; d
= d
->hp_next
)
3032 if (d
->kind
== CK_GROUP
)
3038 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
3040 /* must be Road Warrior: we have a winner */
3045 /* Opportunistic or Shunt: pick tightest match */
3046 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
3047 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
3055 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3056 " but no connection has been authorized%s%s"
3057 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
3058 , (policy
!= LEMPTY
) ?
" with policy=" : ""
3059 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
3060 /* XXX notification is in order! */
3063 else if (c
->kind
!= CK_TEMPLATE
)
3065 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3066 " but \"%s\" forbids connection"
3067 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
3068 /* XXX notification is in order! */
3073 /* Create a temporary connection that is a copy of this one.
3074 * His ID isn't declared yet.
3076 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
3079 else if (c
->kind
== CK_TEMPLATE
)
3081 /* Create an instance
3082 * This is a rare case: wildcard peer ID but static peer IP address
3084 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
3088 md
->st
= st
= new_state();
3089 st
->st_connection
= c
;
3090 set_cur_state(st
); /* (caller will reset cur_state) */
3091 st
->st_try
= 0; /* not our job to try again from start */
3092 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
3094 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
3095 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
3097 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3099 st
->st_doi
= ISAKMP_DOI_IPSEC
;
3100 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
3102 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
3104 plog("responding to Main Mode from unknown peer %s:%u"
3105 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
3107 else if (c
->kind
== CK_INSTANCE
)
3109 plog("responding to Main Mode from unknown peer %s"
3110 , ip_str(&c
->spd
.that
.host_addr
));
3114 plog("responding to Main Mode");
3117 /* parse_isakmp_sa also spits out a winning SA into our reply,
3118 * so we have to build our md->reply and emit HDR before calling it.
3121 /* determine how many Vendor ID payloads we will be sending */
3124 if (SEND_CISCO_UNITY_VID
)
3130 /* always send DPD Vendor ID */
3132 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3136 * We can't leave this to comm_handle() because we must
3137 * fill in the cookie.
3140 struct isakmp_hdr r_hdr
= md
->hdr
;
3142 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
3143 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
3144 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
3145 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
3146 return STF_INTERNAL_ERROR
;
3149 /* start of SA out */
3151 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
3153 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
3155 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
3156 return STF_INTERNAL_ERROR
;
3159 /* SA body in and out */
3160 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
3161 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
3163 /* if enabled send Pluto Vendor ID */
3166 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3167 , &md
->rbody
, VID_STRONGSWAN
))
3169 return STF_INTERNAL_ERROR
;
3173 /* if enabled send Cisco Unity Vendor ID */
3174 if (SEND_CISCO_UNITY_VID
)
3176 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3177 , &md
->rbody
, VID_CISCO_UNITY
))
3179 return STF_INTERNAL_ERROR
;
3184 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3188 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3189 , &md
->rbody
, VID_OPENPGP
))
3191 return STF_INTERNAL_ERROR
;
3195 /* Announce our ability to do eXtended AUTHentication to the peer */
3198 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3199 , &md
->rbody
, VID_MISC_XAUTH
))
3201 return STF_INTERNAL_ERROR
;
3205 /* Announce our ability to do Dead Peer Detection to the peer */
3206 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3207 , &md
->rbody
, VID_MISC_DPD
))
3209 return STF_INTERNAL_ERROR
;
3212 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3214 /* reply if NAT-Traversal draft is supported */
3215 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3217 if (st
->nat_traversal
3218 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3219 , &md
->rbody
, md
->nat_traversal_vid
))
3221 return STF_INTERNAL_ERROR
;
3225 close_message(&md
->rbody
);
3227 /* save initiator SA for HASH */
3228 clonereplacechunk(st
->st_p1isa
, sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
), "sa in main_inI1_outR1()");
3233 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3234 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3236 * The following are not yet implemented:
3237 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3238 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3239 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3241 * We must verify that the proposal received matches one we sent.
3244 main_inR1_outI2(struct msg_digest
*md
)
3246 struct state
*const st
= md
->st
;
3248 u_int8_t np
= ISAKMP_NEXT_NONE
;
3250 /* verify echoed SA */
3252 u_int32_t ipsecdoisit
;
3253 pb_stream proposal_pbs
;
3254 struct isakmp_proposal proposal
;
3255 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3257 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3258 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3259 if (proposal
.isap_notrans
!= 1)
3261 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3262 , (unsigned)proposal
.isap_notrans
);
3263 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3265 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3266 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3269 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3271 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3272 plog("enabling possible NAT-traversal with method %s"
3273 , bitnamesof(natt_type_bitnames
, st
->nat_traversal
));