1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * RCSID $Id: ipsec_doi.c,v 1.39 2006/04/22 21:59:20 as Exp $
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29 #include <sys/time.h> /* for gettimeofday */
32 #include <ipsec_policy.h>
34 #include "constants.h"
43 #include "smartcard.h"
44 #include "connections.h"
47 #include "demux.h" /* needs packet.h */
48 #include "adns.h" /* needs <resolv.h> */
49 #include "dnskey.h" /* needs keys.h and adns.h */
57 #include "ipsec_doi.h" /* needs demux.h and state.h */
65 #include "crypto.h" /* requires sha1.h and md5.h */
69 #include "kernel_alg.h"
70 #include "nat_traversal.h"
74 * are we sending Pluto's Vendor ID?
77 #define SEND_PLUTO_VID 1
79 #define SEND_PLUTO_VID 0
80 #endif /* !VENDORID */
83 * are we sending a Cisco Unity VID?
86 #define SEND_CISCO_UNITY_VID 1
87 #else /* !CISCO_QUIRKS */
88 #define SEND_CISCO_UNITY_VID 0
89 #endif /* !CISCO_QUIRKS */
91 /* MAGIC: perform f, a function that returns notification_t
92 * and return from the ENCLOSING stf_status returning function if it fails.
94 #define RETURN_STF_FAILURE(f) \
95 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
97 /* create output HDR as replica of input HDR */
99 echo_hdr(struct msg_digest
*md
, bool enc
, u_int8_t np
)
101 struct isakmp_hdr r_hdr
= md
->hdr
; /* mostly same as incoming header */
103 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
105 r_hdr
.isa_flags
|= ISAKMP_FLAG_ENCRYPTION
;
106 /* some day, we may have to set r_hdr.isa_version */
108 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
109 impossible(); /* surely must have room and be well-formed */
112 /* Compute DH shared secret from our local secret and the peer's public value.
113 * We make the leap that the length should be that of the group
114 * (see quoted passage at start of ACCEPT_KE).
117 compute_dh_shared(struct state
*st
, const chunk_t g
118 , const struct oakley_group_desc
*group
)
120 MP_INT mp_g
, mp_shared
;
121 struct timeval tv0
, tv1
;
122 unsigned long tv_diff
;
124 gettimeofday(&tv0
, NULL
);
125 passert(st
->st_sec_in_use
);
126 n_to_mpz(&mp_g
, g
.ptr
, g
.len
);
127 mpz_init(&mp_shared
);
128 mpz_powm(&mp_shared
, &mp_g
, &st
->st_sec
, group
->modulus
);
130 freeanychunk(st
->st_shared
); /* happens in odd error cases */
131 st
->st_shared
= mpz_to_n(&mp_shared
, group
->bytes
);
132 mpz_clear(&mp_shared
);
133 gettimeofday(&tv1
, NULL
);
134 tv_diff
=(tv1
.tv_sec
- tv0
.tv_sec
) * 1000000 + (tv1
.tv_usec
- tv0
.tv_usec
);
136 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
137 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
140 /* if took more than 200 msec ... */
141 if (tv_diff
> 200000) {
142 loglog(RC_LOG_SERIOUS
, "WARNING: compute_dh_shared(): for %s took "
144 , enum_show(&oakley_group_names
, st
->st_oakley
.group
->group
)
148 DBG_cond_dump_chunk(DBG_CRYPT
, "DH shared secret:\n", st
->st_shared
);
151 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
152 * the corresponding public value (g). This is emitted as a KE payload.
155 build_and_ship_KE(struct state
*st
, chunk_t
*g
156 , const struct oakley_group_desc
*group
, pb_stream
*outs
, u_int8_t np
)
158 if (!st
->st_sec_in_use
)
160 u_char tmp
[LOCALSECRETSIZE
];
163 get_rnd_bytes(tmp
, LOCALSECRETSIZE
);
164 st
->st_sec_in_use
= TRUE
;
165 n_to_mpz(&st
->st_sec
, tmp
, LOCALSECRETSIZE
);
168 mpz_powm(&mp_g
, &groupgenerator
, &st
->st_sec
, group
->modulus
);
169 freeanychunk(*g
); /* happens in odd error cases */
170 *g
= mpz_to_n(&mp_g
, group
->bytes
);
173 DBG_dump("Local DH secret:\n", tmp
, LOCALSECRETSIZE
);
174 DBG_dump_chunk("Public DH value sent:\n", *g
));
176 return out_generic_chunk(np
, &isakmp_keyex_desc
, outs
, *g
, "keyex value");
181 * Check and accept DH public value (Gi or Gr) from peer's message.
182 * According to RFC2409 "The Internet key exchange (IKE)" 5:
183 * The Diffie-Hellman public value passed in a KE payload, in either
184 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
185 * Diffie-Hellman group enforced, if necessary, by pre-pending the
188 static notification_t
189 accept_KE(chunk_t
*dest
, const char *val_name
190 , const struct oakley_group_desc
*gr
193 if (pbs_left(pbs
) != gr
->bytes
)
195 loglog(RC_LOG_SERIOUS
, "KE has %u byte DH public value; %u required"
196 , (unsigned) pbs_left(pbs
), (unsigned) gr
->bytes
);
197 /* XXX Could send notification back */
198 return INVALID_KEY_INFORMATION
;
200 clonereplacechunk(*dest
, pbs
->cur
, pbs_left(pbs
), val_name
);
201 DBG_cond_dump_chunk(DBG_CRYPT
, "DH public value received:\n", *dest
);
202 return NOTHING_WRONG
;
207 * Check and accept optional Quick Mode KE payload for PFS.
208 * Extends ACCEPT_PFS to check whether KE is allowed or required.
210 static notification_t
211 accept_PFS_KE(struct msg_digest
*md
, chunk_t
*dest
212 , const char *val_name
, const char *msg_name
)
214 struct state
*st
= md
->st
;
215 struct payload_digest
*const ke_pd
= md
->chain
[ISAKMP_NEXT_KE
];
219 if (st
->st_pfs_group
!= NULL
)
221 loglog(RC_LOG_SERIOUS
, "missing KE payload in %s message", msg_name
);
222 return INVALID_KEY_INFORMATION
;
227 if (st
->st_pfs_group
== NULL
)
229 loglog(RC_LOG_SERIOUS
, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
231 return INVALID_KEY_INFORMATION
;
233 if (ke_pd
->next
!= NULL
)
235 loglog(RC_LOG_SERIOUS
, "%s message contains several KE payloads; we accept at most one", msg_name
);
236 return INVALID_KEY_INFORMATION
; /* ??? */
238 return accept_KE(dest
, val_name
, st
->st_pfs_group
, &ke_pd
->pbs
);
240 return NOTHING_WRONG
;
244 build_and_ship_nonce(chunk_t
*n
, pb_stream
*outs
, u_int8_t np
248 setchunk(*n
, alloc_bytes(DEFAULT_NONCE_SIZE
, name
), DEFAULT_NONCE_SIZE
);
249 get_rnd_bytes(n
->ptr
, DEFAULT_NONCE_SIZE
);
250 return out_generic_chunk(np
, &isakmp_nonce_desc
, outs
, *n
, name
);
254 collect_rw_ca_candidates(struct msg_digest
*md
, generalName_t
**top
)
256 struct connection
*d
= find_host_connection(&md
->iface
->addr
257 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, LEMPTY
);
259 for (; d
!= NULL
; d
= d
->hp_next
)
261 /* must be a road warrior connection */
262 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
)
263 && d
->spd
.that
.ca
.ptr
!= NULL
)
266 bool new_entry
= TRUE
;
268 for (gn
= *top
; gn
!= NULL
; gn
= gn
->next
)
270 if (same_dn(gn
->name
, d
->spd
.that
.ca
))
278 gn
= alloc_thing(generalName_t
, "generalName");
279 gn
->kind
= GN_DIRECTORY_NAME
;
280 gn
->name
= d
->spd
.that
.ca
;
290 build_and_ship_CR(u_int8_t type
, chunk_t ca
, pb_stream
*outs
, u_int8_t np
)
293 struct isakmp_cr cr_hd
;
295 cr_hd
.isacr_type
= type
;
297 /* build CR header */
298 if (!out_struct(&cr_hd
, &isakmp_ipsec_cert_req_desc
, outs
, &cr_pbs
))
303 /* build CR body containing the distinguished name of the CA */
304 if (!out_chunk(ca
, &cr_pbs
, "CA"))
307 close_output_pbs(&cr_pbs
);
311 /* Send a notification to the peer. We could decide
312 * whether to send the notification, based on the type and the
313 * destination, if we care to.
316 send_notification(struct state
*sndst
, u_int16_t type
, struct state
*encst
,
317 msgid_t msgid
, u_char
*icookie
, u_char
*rcookie
,
318 u_char
*spi
, size_t spisize
, u_char protoid
)
321 pb_stream pbs
, r_hdr_pbs
;
322 u_char
*r_hashval
= NULL
; /* where in reply to jam hash value */
323 u_char
*r_hash_start
= NULL
; /* start of what is to be hashed */
325 passert((sndst
) && (sndst
->st_connection
));
327 plog("sending %snotification %s to %s:%u"
328 , encst ?
"encrypted " : ""
329 , enum_name(¬ification_names
, type
)
330 , ip_str(&sndst
->st_connection
->spd
.that
.host_addr
)
331 , (unsigned)sndst
->st_connection
->spd
.that
.host_port
);
333 memset(buffer
, 0, sizeof(buffer
));
334 init_pbs(&pbs
, buffer
, sizeof(buffer
), "ISAKMP notify");
338 struct isakmp_hdr hdr
;
340 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
341 hdr
.isa_np
= encst ? ISAKMP_NEXT_HASH
: ISAKMP_NEXT_N
;
342 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
343 hdr
.isa_msgid
= msgid
;
344 hdr
.isa_flags
= encst ? ISAKMP_FLAG_ENCRYPTION
: 0;
346 memcpy(hdr
.isa_icookie
, icookie
, COOKIE_SIZE
);
348 memcpy(hdr
.isa_rcookie
, rcookie
, COOKIE_SIZE
);
349 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &pbs
, &r_hdr_pbs
))
353 /* HASH -- value to be filled later */
357 if (!out_generic(ISAKMP_NEXT_N
, &isakmp_hash_desc
, &r_hdr_pbs
,
360 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
362 encst
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH"))
364 close_output_pbs(&hash_pbs
);
365 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH */
368 /* Notification Payload */
371 struct isakmp_notification isan
;
373 isan
.isan_doi
= ISAKMP_DOI_IPSEC
;
374 isan
.isan_np
= ISAKMP_NEXT_NONE
;
375 isan
.isan_type
= type
;
376 isan
.isan_spisize
= spisize
;
377 isan
.isan_protoid
= protoid
;
379 if (!out_struct(&isan
, &isakmp_notification_desc
, &r_hdr_pbs
, ¬_pbs
)
380 || !out_raw(spi
, spisize
, ¬_pbs
, "spi"))
382 close_output_pbs(¬_pbs
);
385 /* calculate hash value and patch into Hash Payload */
389 hmac_init_chunk(&ctx
, encst
->st_oakley
.hasher
, encst
->st_skeyid_a
);
390 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
391 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
392 hmac_final(r_hashval
, &ctx
);
395 DBG_log("HASH computed:");
396 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
400 /* Encrypt message (preserve st_iv and st_new_iv) */
403 u_char old_iv
[MAX_DIGEST_LEN
];
404 u_char new_iv
[MAX_DIGEST_LEN
];
406 u_int old_iv_len
= encst
->st_iv_len
;
407 u_int new_iv_len
= encst
->st_new_iv_len
;
409 if (old_iv_len
> MAX_DIGEST_LEN
|| new_iv_len
> MAX_DIGEST_LEN
)
412 memcpy(old_iv
, encst
->st_iv
, old_iv_len
);
413 memcpy(new_iv
, encst
->st_new_iv
, new_iv_len
);
415 if (!IS_ISAKMP_SA_ESTABLISHED(encst
->st_state
))
417 memcpy(encst
->st_ph1_iv
, encst
->st_new_iv
, encst
->st_new_iv_len
);
418 encst
->st_ph1_iv_len
= encst
->st_new_iv_len
;
420 init_phase2_iv(encst
, &msgid
);
421 if (!encrypt_message(&r_hdr_pbs
, encst
))
424 /* restore preserved st_iv and st_new_iv */
425 memcpy(encst
->st_iv
, old_iv
, old_iv_len
);
426 memcpy(encst
->st_new_iv
, new_iv
, new_iv_len
);
427 encst
->st_iv_len
= old_iv_len
;
428 encst
->st_new_iv_len
= new_iv_len
;
432 close_output_pbs(&r_hdr_pbs
);
435 /* Send packet (preserve st_tpacket) */
437 chunk_t saved_tpacket
= sndst
->st_tpacket
;
439 setchunk(sndst
->st_tpacket
, pbs
.start
, pbs_offset(&pbs
));
440 send_packet(sndst
, "ISAKMP notify");
441 sndst
->st_tpacket
= saved_tpacket
;
446 send_notification_from_state(struct state
*st
, enum state_kind state
,
453 if (state
== STATE_UNDEFINED
)
454 state
= st
->st_state
;
456 if (IS_QUICK(state
)) {
457 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
458 if ((p1st
== NULL
) || (!IS_ISAKMP_SA_ESTABLISHED(p1st
->st_state
))) {
459 loglog(RC_LOG_SERIOUS
,
460 "no Phase1 state for Quick mode notification");
463 send_notification(st
, type
, p1st
, generate_msgid(p1st
),
464 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
466 else if (IS_ISAKMP_ENCRYPTED(state
)) {
467 send_notification(st
, type
, st
, generate_msgid(st
),
468 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
471 /* no ISAKMP SA established - don't encrypt notification */
472 send_notification(st
, type
, NULL
, 0,
473 st
->st_icookie
, st
->st_rcookie
, NULL
, 0, PROTO_ISAKMP
);
478 send_notification_from_md(struct msg_digest
*md
, u_int16_t type
)
481 * Create a dummy state to be able to use send_packet in
485 * st_connection->that.host_addr
486 * st_connection->that.host_port
487 * st_connection->interface
490 struct connection cnx
;
494 memset(&st
, 0, sizeof(st
));
495 memset(&cnx
, 0, sizeof(cnx
));
496 st
.st_connection
= &cnx
;
497 cnx
.spd
.that
.host_addr
= md
->sender
;
498 cnx
.spd
.that
.host_port
= md
->sender_port
;
499 cnx
.interface
= md
->iface
;
501 send_notification(&st
, type
, NULL
, 0,
502 md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
, NULL
, 0, PROTO_ISAKMP
);
505 /* Send a Delete Notification to announce deletion of ISAKMP SA or
506 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
507 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
510 send_delete(struct state
*st
)
517 ip_said said
[EM_MAXRELSPIS
];
520 *r_hashval
, /* where in reply to jam hash value */
521 *r_hash_start
; /* start of what is to be hashed */
522 bool isakmp_sa
= FALSE
;
524 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
526 p1st
= find_phase1_state(st
->st_connection
, ISAKMP_SA_ESTABLISHED_STATES
);
529 DBG(DBG_CONTROL
, DBG_log("no Phase 1 state for Delete"));
533 if (st
->st_ah
.present
)
535 ns
->spi
= st
->st_ah
.our_spi
;
536 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
537 ns
->proto
= PROTO_IPSEC_AH
;
540 if (st
->st_esp
.present
)
542 ns
->spi
= st
->st_esp
.our_spi
;
543 ns
->dst
= st
->st_connection
->spd
.this.host_addr
;
544 ns
->proto
= PROTO_IPSEC_ESP
;
548 passert(ns
!= said
); /* there must be some SAs to delete */
550 else if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
557 return; /* nothing to do */
560 msgid
= generate_msgid(p1st
);
563 init_pbs(&reply_pbs
, buffer
, sizeof(buffer
), "delete msg");
567 struct isakmp_hdr hdr
;
569 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
570 hdr
.isa_np
= ISAKMP_NEXT_HASH
;
571 hdr
.isa_xchg
= ISAKMP_XCHG_INFO
;
572 hdr
.isa_msgid
= msgid
;
573 hdr
.isa_flags
= ISAKMP_FLAG_ENCRYPTION
;
574 memcpy(hdr
.isa_icookie
, p1st
->st_icookie
, COOKIE_SIZE
);
575 memcpy(hdr
.isa_rcookie
, p1st
->st_rcookie
, COOKIE_SIZE
);
576 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply_pbs
, &r_hdr_pbs
))
580 /* HASH -- value to be filled later */
584 if (!out_generic(ISAKMP_NEXT_D
, &isakmp_hash_desc
, &r_hdr_pbs
, &hash_pbs
))
586 r_hashval
= hash_pbs
.cur
; /* remember where to plant value */
587 if (!out_zero(p1st
->st_oakley
.hasher
->hash_digest_size
, &hash_pbs
, "HASH(1)"))
589 close_output_pbs(&hash_pbs
);
590 r_hash_start
= r_hdr_pbs
.cur
; /* hash from after HASH(1) */
593 /* Delete Payloads */
597 struct isakmp_delete isad
;
598 u_char isakmp_spi
[2*COOKIE_SIZE
];
600 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
601 isad
.isad_np
= ISAKMP_NEXT_NONE
;
602 isad
.isad_spisize
= (2 * COOKIE_SIZE
);
603 isad
.isad_protoid
= PROTO_ISAKMP
;
606 memcpy(isakmp_spi
, st
->st_icookie
, COOKIE_SIZE
);
607 memcpy(isakmp_spi
+COOKIE_SIZE
, st
->st_rcookie
, COOKIE_SIZE
);
609 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
610 || !out_raw(&isakmp_spi
, (2*COOKIE_SIZE
), &del_pbs
, "delete payload"))
612 close_output_pbs(&del_pbs
);
620 struct isakmp_delete isad
;
623 isad
.isad_doi
= ISAKMP_DOI_IPSEC
;
624 isad
.isad_np
= ns
== said? ISAKMP_NEXT_NONE
: ISAKMP_NEXT_D
;
625 isad
.isad_spisize
= sizeof(ipsec_spi_t
);
626 isad
.isad_protoid
= ns
->proto
;
629 if (!out_struct(&isad
, &isakmp_delete_desc
, &r_hdr_pbs
, &del_pbs
)
630 || !out_raw(&ns
->spi
, sizeof(ipsec_spi_t
), &del_pbs
, "delete payload"))
632 close_output_pbs(&del_pbs
);
636 /* calculate hash value and patch into Hash Payload */
639 hmac_init_chunk(&ctx
, p1st
->st_oakley
.hasher
, p1st
->st_skeyid_a
);
640 hmac_update(&ctx
, (u_char
*) &msgid
, sizeof(msgid_t
));
641 hmac_update(&ctx
, r_hash_start
, r_hdr_pbs
.cur
-r_hash_start
);
642 hmac_final(r_hashval
, &ctx
);
645 DBG_log("HASH(1) computed:");
646 DBG_dump("", r_hashval
, ctx
.hmac_digest_size
);
650 /* Do a dance to avoid needing a new state object.
651 * We use the Phase 1 State. This is the one with right
653 * The tricky bits are:
654 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
655 * - we need to preserve (save/restore) st_tpacket.
658 u_char old_iv
[MAX_DIGEST_LEN
];
659 chunk_t saved_tpacket
= p1st
->st_tpacket
;
661 memcpy(old_iv
, p1st
->st_iv
, p1st
->st_iv_len
);
662 init_phase2_iv(p1st
, &msgid
);
664 if (!encrypt_message(&r_hdr_pbs
, p1st
))
667 setchunk(p1st
->st_tpacket
, reply_pbs
.start
, pbs_offset(&reply_pbs
));
668 send_packet(p1st
, "delete notify");
669 p1st
->st_tpacket
= saved_tpacket
;
671 /* get back old IV for this state */
672 memcpy(p1st
->st_iv
, old_iv
, p1st
->st_iv_len
);
677 accept_delete(struct state
*st
, struct msg_digest
*md
, struct payload_digest
*p
)
679 struct isakmp_delete
*d
= &(p
->payload
.delete);
685 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: not encrypted");
689 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
691 /* can't happen (if msg is encrypt), but just to be sure */
692 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
693 "ISAKMP SA not established");
697 if (d
->isad_nospi
== 0)
699 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: no SPI");
703 switch (d
->isad_protoid
)
706 sizespi
= 2 * COOKIE_SIZE
;
709 case PROTO_IPSEC_ESP
:
710 sizespi
= sizeof(ipsec_spi_t
);
713 /* nothing interesting to delete */
716 loglog(RC_LOG_SERIOUS
717 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
718 , enum_show(&protocol_names
, d
->isad_protoid
));
722 if (d
->isad_spisize
!= sizespi
)
724 loglog(RC_LOG_SERIOUS
725 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
726 , d
->isad_spisize
, enum_show(&protocol_names
, d
->isad_protoid
));
730 if (pbs_left(&p
->pbs
) != d
->isad_nospi
* sizespi
)
732 loglog(RC_LOG_SERIOUS
733 , "ignoring Delete SA payload: invalid payload size");
737 for (i
= 0; i
< d
->isad_nospi
; i
++)
739 u_char
*spi
= p
->pbs
.cur
+ (i
* sizespi
);
741 if (d
->isad_protoid
== PROTO_ISAKMP
)
746 struct state
*dst
= find_state(spi
/*iCookie*/
747 , spi
+COOKIE_SIZE
/*rCookie*/
748 , &st
->st_connection
->spd
.that
.host_addr
753 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
754 "ISAKMP SA not found (maybe expired)");
756 else if (!same_peer_ids(st
->st_connection
, dst
->st_connection
, NULL
))
758 /* we've not authenticated the relevant identities */
759 loglog(RC_LOG_SERIOUS
, "ignoring Delete SA payload: "
760 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
764 struct connection
*oldc
;
766 oldc
= cur_connection
;
767 set_cur_connection(dst
->st_connection
);
769 if (nat_traversal_enabled
)
770 nat_traversal_change_port_lookup(md
, dst
);
772 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
773 "deleting ISAKMP State #%lu", dst
->st_serialno
);
775 set_cur_connection(oldc
);
784 struct state
*dst
= find_phase2_state_to_delete(st
786 , *(ipsec_spi_t
*)spi
/* network order */
791 loglog(RC_LOG_SERIOUS
792 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
793 , enum_show(&protocol_names
, d
->isad_protoid
)
794 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
795 , bogus ?
"our SPI - bogus implementation" : "maybe expired");
799 struct connection
*rc
= dst
->st_connection
;
800 struct connection
*oldc
;
802 oldc
= cur_connection
;
803 set_cur_connection(rc
);
805 if (nat_traversal_enabled
)
806 nat_traversal_change_port_lookup(md
, dst
);
808 if (rc
->newest_ipsec_sa
== dst
->st_serialno
809 && (rc
->policy
& POLICY_UP
))
811 /* Last IPSec SA for a permanent connection that we
812 * have initiated. Replace it in a few seconds.
814 * Useful if the other peer is rebooting.
816 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
817 if (dst
->st_event
!= NULL
818 && dst
->st_event
->ev_type
== EVENT_SA_REPLACE
819 && dst
->st_event
->ev_time
<= DELETE_SA_DELAY
+ now())
821 /* Patch from Angus Lees to ignore retransmited
824 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
825 "already replacing IPSEC State #%lu in %d seconds"
826 , dst
->st_serialno
, (int)(dst
->st_event
->ev_time
- now()));
830 loglog(RC_LOG_SERIOUS
, "received Delete SA payload: "
831 "replace IPSEC State #%lu in %d seconds"
832 , dst
->st_serialno
, DELETE_SA_DELAY
);
833 dst
->st_margin
= DELETE_SA_DELAY
;
835 event_schedule(EVENT_SA_REPLACE
, DELETE_SA_DELAY
, dst
);
840 loglog(RC_LOG_SERIOUS
, "received Delete SA(0x%08lx) payload: "
841 "deleting IPSEC State #%lu"
842 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t
*)spi
)
847 /* reset connection */
848 set_cur_connection(oldc
);
854 /* The whole message must be a multiple of 4 octets.
855 * I'm not sure where this is spelled out, but look at
856 * rfc2408 3.6 Transform Payload.
857 * Note: it talks about 4 BYTE boundaries!
860 close_message(pb_stream
*pbs
)
862 size_t padding
= pad_up(pbs_offset(pbs
), 4);
865 (void) out_zero(padding
, pbs
, "message padding");
866 close_output_pbs(pbs
);
869 /* Initiate an Oakley Main Mode exchange.
871 * Note: this is not called from demux.c
874 main_outI1(int whack_sock
, struct connection
*c
, struct state
*predecessor
875 , lset_t policy
, unsigned long try)
877 struct state
*st
= new_state();
878 pb_stream reply
; /* not actually a reply, but you know what I mean */
881 int vids_to_send
= 0;
883 /* set up new state */
884 st
->st_connection
= c
;
885 set_cur_state(st
); /* we must reset before exit */
886 st
->st_policy
= policy
& ~POLICY_IPSEC_MASK
;
887 st
->st_whack_sock
= whack_sock
;
889 st
->st_state
= STATE_MAIN_I1
;
891 /* determine how many Vendor ID payloads we will be sending */
894 if (SEND_CISCO_UNITY_VID
)
896 if (c
->spd
.this.cert
.type
== CERT_PGP
)
898 /* always send XAUTH Vendor ID */
900 /* always send DPD Vendor ID */
902 if (nat_traversal_enabled
)
905 get_cookie(TRUE
, st
->st_icookie
, COOKIE_SIZE
, &c
->spd
.that
.host_addr
);
907 insert_state(st
); /* needs cookies, connection, and msgid (0) */
909 if (HAS_IPSEC_POLICY(policy
))
910 add_pending(dup_any(whack_sock
), st
, c
, policy
, 1
911 , predecessor
== NULL? SOS_NOBODY
: predecessor
->st_serialno
);
913 if (predecessor
== NULL
)
914 plog("initiating Main Mode");
916 plog("initiating Main Mode to replace #%lu", predecessor
->st_serialno
);
919 init_pbs(&reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
923 struct isakmp_hdr hdr
;
925 zero(&hdr
); /* default to 0 */
926 hdr
.isa_version
= ISAKMP_MAJOR_VERSION
<< ISA_MAJ_SHIFT
| ISAKMP_MINOR_VERSION
;
927 hdr
.isa_np
= ISAKMP_NEXT_SA
;
928 hdr
.isa_xchg
= ISAKMP_XCHG_IDPROT
;
929 memcpy(hdr
.isa_icookie
, st
->st_icookie
, COOKIE_SIZE
);
930 /* R-cookie, flags and MessageID are left zero */
932 if (!out_struct(&hdr
, &isakmp_hdr_desc
, &reply
, &rbody
))
935 return STF_INTERNAL_ERROR
;
941 u_char
*sa_start
= rbody
.cur
;
942 lset_t auth_policy
= policy
& POLICY_ID_AUTH_MASK
;
944 if (!out_sa(&rbody
, &oakley_sadb
, st
, TRUE
945 , vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
))
948 return STF_INTERNAL_ERROR
;
951 /* save initiator SA for later HASH */
952 passert(st
->st_p1isa
.ptr
== NULL
); /* no leak! (MUST be first time) */
953 clonetochunk(st
->st_p1isa
, sa_start
, rbody
.cur
- sa_start
954 , "sa in main_outI1");
957 /* if enabled send Pluto Vendor ID */
960 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
961 , &rbody
, VID_STRONGSWAN
))
964 return STF_INTERNAL_ERROR
;
968 /* if enabled send Cisco Unity Vendor ID */
969 if (SEND_CISCO_UNITY_VID
)
971 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
972 , &rbody
, VID_CISCO_UNITY
))
975 return STF_INTERNAL_ERROR
;
978 /* if we have an OpenPGP certificate we assume an
979 * OpenPGP peer and have to send the Vendor ID
981 if (c
->spd
.this.cert
.type
== CERT_PGP
)
983 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
984 , &rbody
, VID_OPENPGP
))
987 return STF_INTERNAL_ERROR
;
991 /* Announce our ability to do eXtended AUTHentication to the peer */
992 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
993 , &rbody
, VID_MISC_XAUTH
))
996 return STF_INTERNAL_ERROR
;
999 /* Announce our ability to do Dead Peer Detection to the peer */
1001 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1002 , &rbody
, VID_MISC_DPD
))
1005 return STF_INTERNAL_ERROR
;
1009 if (nat_traversal_enabled
)
1011 /* Add supported NAT-Traversal VID */
1012 if (!nat_traversal_add_vid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
1016 return STF_INTERNAL_ERROR
;
1020 close_message(&rbody
);
1021 close_output_pbs(&reply
);
1023 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
1024 , "reply packet for main_outI1");
1028 send_packet(st
, "main_outI1");
1030 /* Set up a retransmission event, half a minute henceforth */
1032 event_schedule(EVENT_RETRANSMIT
, EVENT_RETRANSMIT_DELAY_0
, st
);
1034 if (predecessor
!= NULL
)
1036 update_pending(predecessor
, st
);
1037 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1038 , "%s: initiate, replacing #%lu"
1039 , enum_name(&state_names
, st
->st_state
)
1040 , predecessor
->st_serialno
);
1044 whack_log(RC_NEW_STATE
+ STATE_MAIN_I1
1045 , "%s: initiate", enum_name(&state_names
, st
->st_state
));
1052 ipsecdoi_initiate(int whack_sock
1053 , struct connection
*c
1056 , so_serial_t replacing
)
1058 /* If there's already an ISAKMP SA established, use that and
1059 * go directly to Quick Mode. We are even willing to use one
1060 * that is still being negotiated, but only if we are the Initiator
1061 * (thus we can be sure that the IDs are not going to change;
1062 * other issues around intent might matter).
1063 * Note: there is no way to initiate with a Road Warrior.
1065 struct state
*st
= find_phase1_state(c
1066 , ISAKMP_SA_ESTABLISHED_STATES
| PHASE1_INITIATOR_STATES
);
1070 (void) main_outI1(whack_sock
, c
, NULL
, policy
, try);
1072 else if (HAS_IPSEC_POLICY(policy
))
1074 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1076 /* leave our Phase 2 negotiation pending */
1077 add_pending(whack_sock
, st
, c
, policy
, try, replacing
);
1081 /* ??? we assume that peer_nexthop_sin isn't important:
1082 * we already have it from when we negotiated the ISAKMP SA!
1083 * It isn't clear what to do with the error return.
1085 (void) quick_outI1(whack_sock
, st
, c
, policy
, try, replacing
);
1090 close_any(whack_sock
);
1094 /* Replace SA with a fresh one that is similar
1096 * Shares some logic with ipsecdoi_initiate, but not the same!
1097 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1098 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1099 * ISAKMP SA if needed.
1100 * - duplicate whack fd, if live.
1101 * Does not delete the old state -- someone else will do that.
1104 ipsecdoi_replace(struct state
*st
, unsigned long try)
1106 int whack_sock
= dup_any(st
->st_whack_sock
);
1107 lset_t policy
= st
->st_policy
;
1109 if (IS_PHASE1(st
->st_state
))
1111 passert(!HAS_IPSEC_POLICY(policy
));
1112 (void) main_outI1(whack_sock
, st
->st_connection
, st
, policy
, try);
1116 /* Add features of actual old state to policy. This ensures
1117 * that rekeying doesn't downgrade security. I admit that
1118 * this doesn't capture everything.
1120 if (st
->st_pfs_group
!= NULL
)
1121 policy
|= POLICY_PFS
;
1122 if (st
->st_ah
.present
)
1124 policy
|= POLICY_AUTHENTICATE
;
1125 if (st
->st_ah
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1126 policy
|= POLICY_TUNNEL
;
1128 if (st
->st_esp
.present
&& st
->st_esp
.attrs
.transid
!= ESP_NULL
)
1130 policy
|= POLICY_ENCRYPT
;
1131 if (st
->st_esp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1132 policy
|= POLICY_TUNNEL
;
1134 if (st
->st_ipcomp
.present
)
1136 policy
|= POLICY_COMPRESS
;
1137 if (st
->st_ipcomp
.attrs
.encapsulation
== ENCAPSULATION_MODE_TUNNEL
)
1138 policy
|= POLICY_TUNNEL
;
1140 passert(HAS_IPSEC_POLICY(policy
));
1141 ipsecdoi_initiate(whack_sock
, st
->st_connection
, policy
, try
1146 /* SKEYID for preshared keys.
1147 * See draft-ietf-ipsec-ike-01.txt 4.1
1150 skeyid_preshared(struct state
*st
)
1152 const chunk_t
*pss
= get_preshared_secret(st
->st_connection
);
1156 loglog(RC_LOG_SERIOUS
, "preshared secret disappeared!");
1161 struct hmac_ctx ctx
;
1163 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, *pss
);
1164 hmac_update_chunk(&ctx
, st
->st_ni
);
1165 hmac_update_chunk(&ctx
, st
->st_nr
);
1166 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_preshared()", &ctx
);
1172 skeyid_digisig(struct state
*st
)
1174 struct hmac_ctx ctx
;
1177 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1178 * so we have to build a temporary concatentation.
1180 nir
.len
= st
->st_ni
.len
+ st
->st_nr
.len
;
1181 nir
.ptr
= alloc_bytes(nir
.len
, "Ni + Nr in skeyid_digisig");
1182 memcpy(nir
.ptr
, st
->st_ni
.ptr
, st
->st_ni
.len
);
1183 memcpy(nir
.ptr
+st
->st_ni
.len
, st
->st_nr
.ptr
, st
->st_nr
.len
);
1184 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, nir
);
1187 hmac_update_chunk(&ctx
, st
->st_shared
);
1188 hmac_final_chunk(st
->st_skeyid
, "st_skeyid in skeyid_digisig()", &ctx
);
1192 /* Generate the SKEYID_* and new IV
1193 * See draft-ietf-ipsec-ike-01.txt 4.1
1196 generate_skeyids_iv(struct state
*st
)
1198 /* Generate the SKEYID */
1199 switch (st
->st_oakley
.auth
)
1201 case OAKLEY_PRESHARED_KEY
:
1202 case XAUTHInitPreShared
:
1203 case XAUTHRespPreShared
:
1204 if (!skeyid_preshared(st
))
1208 case OAKLEY_RSA_SIG
:
1211 if (!skeyid_digisig(st
))
1215 case OAKLEY_DSS_SIG
:
1218 case OAKLEY_RSA_ENC
:
1219 case OAKLEY_RSA_ENC_REV
:
1220 case OAKLEY_ELGAMAL_ENC
:
1221 case OAKLEY_ELGAMAL_ENC_REV
:
1225 bad_case(st
->st_oakley
.auth
);
1228 /* generate SKEYID_* from SKEYID */
1230 struct hmac_ctx ctx
;
1232 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1235 hmac_update_chunk(&ctx
, st
->st_shared
);
1236 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1237 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1238 hmac_update(&ctx
, "\0", 1);
1239 hmac_final_chunk(st
->st_skeyid_d
, "st_skeyid_d in generate_skeyids_iv()", &ctx
);
1243 hmac_update_chunk(&ctx
, st
->st_skeyid_d
);
1244 hmac_update_chunk(&ctx
, st
->st_shared
);
1245 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1246 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1247 hmac_update(&ctx
, "\1", 1);
1248 hmac_final_chunk(st
->st_skeyid_a
, "st_skeyid_a in generate_skeyids_iv()", &ctx
);
1252 hmac_update_chunk(&ctx
, st
->st_skeyid_a
);
1253 hmac_update_chunk(&ctx
, st
->st_shared
);
1254 hmac_update(&ctx
, st
->st_icookie
, COOKIE_SIZE
);
1255 hmac_update(&ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1256 hmac_update(&ctx
, "\2", 1);
1257 hmac_final_chunk(st
->st_skeyid_e
, "st_skeyid_e in generate_skeyids_iv()", &ctx
);
1262 union hash_ctx hash_ctx
;
1263 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1265 st
->st_new_iv_len
= h
->hash_digest_size
;
1266 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1269 DBG_dump_chunk("DH_i:", st
->st_gi
);
1270 DBG_dump_chunk("DH_r:", st
->st_gr
);
1272 h
->hash_init(&hash_ctx
);
1273 h
->hash_update(&hash_ctx
, st
->st_gi
.ptr
, st
->st_gi
.len
);
1274 h
->hash_update(&hash_ctx
, st
->st_gr
.ptr
, st
->st_gr
.len
);
1275 h
->hash_final(st
->st_new_iv
, &hash_ctx
);
1278 /* Oakley Keying Material
1279 * Derived from Skeyid_e: if it is not big enough, generate more
1281 * See RFC 2409 "IKE" Appendix B
1284 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1285 const size_t keysize
= st
->st_oakley
.enckeylen
/BITS_PER_BYTE
;
1286 u_char keytemp
[MAX_OAKLEY_KEY_LEN
+ MAX_DIGEST_LEN
];
1287 u_char
*k
= st
->st_skeyid_e
.ptr
;
1289 if (keysize
> st
->st_skeyid_e
.len
)
1291 struct hmac_ctx ctx
;
1294 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_e
);
1295 hmac_update(&ctx
, "\0", 1);
1298 hmac_final(&keytemp
[i
], &ctx
);
1299 i
+= ctx
.hmac_digest_size
;
1303 hmac_update(&ctx
, &keytemp
[i
- ctx
.hmac_digest_size
], ctx
.hmac_digest_size
);
1307 clonereplacechunk(st
->st_enc_key
, k
, keysize
, "st_enc_key");
1311 DBG_dump_chunk("Skeyid: ", st
->st_skeyid
);
1312 DBG_dump_chunk("Skeyid_d:", st
->st_skeyid_d
);
1313 DBG_dump_chunk("Skeyid_a:", st
->st_skeyid_a
);
1314 DBG_dump_chunk("Skeyid_e:", st
->st_skeyid_e
);
1315 DBG_dump_chunk("enc key:", st
->st_enc_key
);
1316 DBG_dump("IV:", st
->st_new_iv
, st
->st_new_iv_len
));
1320 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1321 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1322 * New Group Mode, or ISAKMP Informational Exchanges).
1323 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1324 * If hashus argument is TRUE, we're generating a hash for our end.
1325 * See RFC2409 IKE 5.
1327 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1328 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1329 * The extensive common logic is embodied in main_mode_hash_body().
1330 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1333 typedef void (*hash_update_t
)(union hash_ctx
*, const u_char
*, size_t) ;
1335 main_mode_hash_body(struct state
*st
1336 , bool hashi
/* Initiator? */
1337 , const pb_stream
*idpl
/* ID payload, as PBS */
1338 , union hash_ctx
*ctx
1339 , void (*hash_update_void
)(void *, const u_char
*input
, size_t))
1341 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1342 hash_update_t hash_update
=(hash_update_t
) hash_update_void
;
1343 #if 0 /* if desperate to debug hashing */
1344 # define hash_update(ctx, input, len) { \
1345 DBG_dump("hash input", input, len); \
1346 (hash_update)(ctx, input, len); \
1350 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1354 hash_update_chunk(ctx
, st
->st_gi
);
1355 hash_update_chunk(ctx
, st
->st_gr
);
1356 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1357 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1361 hash_update_chunk(ctx
, st
->st_gr
);
1362 hash_update_chunk(ctx
, st
->st_gi
);
1363 hash_update(ctx
, st
->st_rcookie
, COOKIE_SIZE
);
1364 hash_update(ctx
, st
->st_icookie
, COOKIE_SIZE
);
1367 DBG(DBG_CRYPT
, DBG_log("hashing %lu bytes of SA"
1368 , (unsigned long) (st
->st_p1isa
.len
- sizeof(struct isakmp_generic
))));
1371 hash_update(ctx
, st
->st_p1isa
.ptr
+ sizeof(struct isakmp_generic
)
1372 , st
->st_p1isa
.len
- sizeof(struct isakmp_generic
));
1374 /* Hash identification payload, without generic payload header.
1375 * We used to reconstruct ID Payload for this purpose, but now
1376 * we use the bytes as they appear on the wire to avoid
1377 * "spelling problems".
1380 , idpl
->start
+ sizeof(struct isakmp_generic
)
1381 , pbs_offset(idpl
) - sizeof(struct isakmp_generic
));
1383 # undef hash_update_chunk
1387 static size_t /* length of hash */
1388 main_mode_hash(struct state
*st
1389 , u_char
*hash_val
/* resulting bytes */
1390 , bool hashi
/* Initiator? */
1391 , const pb_stream
*idpl
) /* ID payload, as PBS; cur must be at end */
1393 struct hmac_ctx ctx
;
1395 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid
);
1396 main_mode_hash_body(st
, hashi
, idpl
, &ctx
.hash_ctx
, ctx
.h
->hash_update
);
1397 hmac_final(hash_val
, &ctx
);
1398 return ctx
.hmac_digest_size
;
1401 #if 0 /* only needed for DSS */
1403 main_mode_sha1(struct state
*st
1404 , u_char
*hash_val
/* resulting bytes */
1405 , size_t *hash_len
/* length of hash */
1406 , bool hashi
/* Initiator? */
1407 , const pb_stream
*idpl
) /* ID payload, as PBS */
1411 SHA1Init(&ctx
.ctx_sha1
);
1412 SHA1Update(&ctx
.ctx_sha1
, st
->st_skeyid
.ptr
, st
->st_skeyid
.len
);
1413 *hash_len
= SHA1_DIGEST_SIZE
;
1414 main_mode_hash_body(st
, hashi
, idpl
, &ctx
1415 , (void (*)(union hash_ctx
*, const u_char
*, unsigned int))&SHA1Update
);
1416 SHA1Final(hash_val
, &ctx
.ctx_sha1
);
1420 /* Create an RSA signature of a hash.
1421 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1422 * Use PKCS#1 version 1.5 encryption of hash (called
1423 * RSAES-PKCS1-V1_5) in PKCS#2.
1426 RSA_sign_hash(struct connection
*c
1427 , u_char sig_val
[RSA_MAX_OCTETS
]
1428 , const u_char
*hash_val
, size_t hash_len
)
1431 smartcard_t
*sc
= c
->spd
.this.sc
;
1433 if (sc
== NULL
) /* no smartcard */
1435 const struct RSA_private_key
*k
= get_RSA_private_key(c
);
1438 return 0; /* failure: no key to use */
1441 passert(RSA_MIN_OCTETS
<= sz
&& 4 + hash_len
< sz
&& sz
<= RSA_MAX_OCTETS
);
1442 sign_hash(k
, hash_val
, hash_len
, sig_val
, sz
);
1444 else if (sc
->valid
) /* if valid pin then sign hash on the smartcard */
1446 lock_certs_and_keys("RSA_sign_hash");
1447 if (!scx_establish_context(sc
) || !scx_login(sc
))
1449 scx_release_context(sc
);
1450 unlock_certs_and_keys("RSA_sign_hash");
1454 sz
= scx_get_keylength(sc
);
1457 plog("failed to get keylength from smartcard");
1458 scx_release_context(sc
);
1459 unlock_certs_and_keys("RSA_sign_hash");
1463 DBG(DBG_CONTROL
| DBG_CRYPT
,
1464 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1465 , (int)sc
->slot
, sc
->id
)
1467 sz
= scx_sign_hash(sc
, hash_val
, hash_len
, sig_val
, sz
) ? sz
: 0;
1468 if (!pkcs11_keep_state
)
1469 scx_release_context(sc
);
1470 unlock_certs_and_keys("RSA_sign_hash");
1475 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1477 * As a side effect, on success, the public key is copied into the
1478 * state object to record the authenticator.
1480 * Can fail because wrong public key is used or because hash disagrees.
1481 * We distinguish because diagnostics should also.
1483 * The result is NULL if the Signature checked out.
1484 * Otherwise, the first character of the result indicates
1485 * how far along failure occurred. A greater character signifies
1489 * 0 reserved for caller
1490 * 1 SIG length doesn't match key length -- wrong key
1491 * 2-8 malformed ECB after decryption -- probably wrong key
1492 * 9 decrypted hash != computed hash -- probably correct key
1494 * Although the math should be the same for generating and checking signatures,
1495 * it is not: the knowledge of the private key allows more efficient (i.e.
1496 * different) computation for encryption.
1499 try_RSA_signature(const u_char hash_val
[MAX_DIGEST_LEN
], size_t hash_len
1500 , const pb_stream
*sig_pbs
, pubkey_t
*kr
1503 const u_char
*sig_val
= sig_pbs
->cur
;
1504 size_t sig_len
= pbs_left(sig_pbs
);
1505 u_char s
[RSA_MAX_OCTETS
]; /* for decrypted sig_val */
1506 u_char
*hash_in_s
= &s
[sig_len
- hash_len
];
1507 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1509 /* decrypt the signature -- reversing RSA_sign_hash */
1510 if (sig_len
!= k
->k
)
1512 /* XXX notification: INVALID_KEY_INFORMATION */
1513 return "1" "SIG length does not match public key length";
1516 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1521 n_to_mpz(c
, sig_val
, sig_len
);
1522 mpz_powm(c
, c
, &k
->e
, &k
->n
);
1524 temp_s
= mpz_to_n(c
, sig_len
); /* back to octets */
1525 memcpy(s
, temp_s
.ptr
, sig_len
);
1530 /* sanity check on signature: see if it matches
1531 * PKCS#1 v1.5 8.1 encryption-block formatting
1537 ugh
= "2" "no leading 00";
1538 else if (hash_in_s
[-1] != 0x00)
1539 ugh
= "3" "00 separator not present";
1540 else if (s
[1] == 0x01)
1544 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1548 ugh
= "4" "invalid Padding String";
1553 else if (s
[1] == 0x02)
1557 for (p
= &s
[2]; p
!= hash_in_s
- 1; p
++)
1561 ugh
= "5" "invalid Padding String";
1567 ugh
= "6" "Block Type not 01 or 02";
1571 /* note: it might be a good idea to make sure that
1572 * an observer cannot tell what kind of failure happened.
1573 * I don't know what this means in practice.
1575 /* We probably selected the wrong public key for peer:
1576 * SIG Payload decrypted into malformed ECB
1578 /* XXX notification: INVALID_KEY_INFORMATION */
1583 /* We have the decoded hash: see if it matches. */
1584 if (memcmp(hash_val
, hash_in_s
, hash_len
) != 0)
1586 /* good: header, hash, signature, and other payloads well-formed
1587 * good: we could find an RSA Sig key for the peer.
1588 * bad: hash doesn't match
1589 * Guess: sides disagree about key to be used.
1591 DBG_cond_dump(DBG_CRYPT
, "decrypted SIG", s
, sig_len
);
1592 DBG_cond_dump(DBG_CRYPT
, "computed HASH", hash_val
, hash_len
);
1593 /* XXX notification: INVALID_HASH_INFORMATION */
1594 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1597 /* Success: copy successful key into state.
1598 * There might be an old one if we previously aborted this
1601 unreference_key(&st
->st_peer_pubkey
);
1602 st
->st_peer_pubkey
= reference_key(kr
);
1604 return NULL
; /* happy happy */
1607 /* Check signature against all RSA public keys we can find.
1608 * If we need keys from DNS KEY records, and they haven't been fetched,
1609 * return STF_SUSPEND to ask for asynch DNS lookup.
1611 * Note: parameter keys_from_dns contains results of DNS lookup for key
1612 * or is NULL indicating lookup not yet tried.
1614 * take_a_crack is a helper function. Mostly forensic.
1615 * If only we had coroutines.
1618 /* RSA_check_signature's args that take_a_crack needs */
1620 const u_char
*hash_val
;
1622 const pb_stream
*sig_pbs
;
1624 /* state carried between calls */
1625 err_t best_ugh
; /* most successful failure */
1626 int tried_cnt
; /* number of keys tried */
1627 char tried
[50]; /* keyids of tried public keys */
1628 char *tn
; /* roof of tried[] */
1632 take_a_crack(struct tac_state
*s
1634 , const char *story USED_BY_DEBUG
)
1636 err_t ugh
= try_RSA_signature(s
->hash_val
, s
->hash_len
, s
->sig_pbs
1638 const struct RSA_public_key
*k
= &kr
->u
.rsa
;
1643 DBG(DBG_CRYPT
| DBG_CONTROL
1644 , DBG_log("an RSA Sig check passed with *%s [%s]"
1645 , k
->keyid
, story
));
1651 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1652 , ugh
+ 1, k
->keyid
, story
));
1653 if (s
->best_ugh
== NULL
|| s
->best_ugh
[0] < ugh
[0])
1656 && s
->tn
- s
->tried
+ KEYID_BUF
+ 2 < (ptrdiff_t)sizeof(s
->tried
))
1658 strcpy(s
->tn
, " *");
1659 strcpy(s
->tn
+ 2, k
->keyid
);
1660 s
->tn
+= strlen(s
->tn
);
1667 RSA_check_signature(const struct id
* peer
1669 , const u_char hash_val
[MAX_DIGEST_LEN
]
1671 , const pb_stream
*sig_pbs
1673 , const pubkey_list_t
*keys_from_dns
1674 #endif /* USE_KEYRR */
1675 , const struct gw_info
*gateways_from_dns
1678 const struct connection
*c
= st
->st_connection
;
1680 err_t dns_ugh
= NULL
;
1683 s
.hash_val
= hash_val
;
1684 s
.hash_len
= hash_len
;
1685 s
.sig_pbs
= sig_pbs
;
1691 /* try all gateway records hung off c */
1692 if (c
->policy
& POLICY_OPPO
)
1696 for (gw
= c
->gw_info
; gw
!= NULL
; gw
= gw
->next
)
1698 /* only consider entries that have a key and are for our peer */
1699 if (gw
->gw_key_present
1700 && same_id(&gw
->gw_id
, &c
->spd
.that
.id
)
1701 && take_a_crack(&s
, gw
->key
, "key saved from DNS TXT"))
1706 /* try all appropriate Public keys */
1708 pubkey_list_t
*p
, **pp
;
1712 for (p
= pubkeys
; p
!= NULL
; p
= *pp
)
1714 pubkey_t
*key
= p
->key
;
1716 if (key
->alg
== PUBKEY_ALG_RSA
&& same_id(peer
, &key
->id
))
1718 time_t now
= time(NULL
);
1720 /* check if found public key has expired */
1721 if (key
->until_time
!= UNDEFINED_TIME
&& key
->until_time
< now
)
1723 loglog(RC_LOG_SERIOUS
,
1724 "cached RSA public key has expired and has been deleted");
1725 *pp
= free_public_keyentry(p
);
1726 continue; /* continue with next public key */
1729 if (take_a_crack(&s
, key
, "preloaded key"))
1736 /* if no key was found (evidenced by best_ugh == NULL)
1737 * and that side of connection is key_from_DNS_on_demand
1738 * then go search DNS for keys for peer.
1740 if (s
.best_ugh
== NULL
&& c
->spd
.that
.key_from_DNS_on_demand
)
1742 if (gateways_from_dns
!= NULL
)
1745 const struct gw_info
*gwp
;
1747 for (gwp
= gateways_from_dns
; gwp
!= NULL
; gwp
= gwp
->next
)
1748 if (gwp
->gw_key_present
1749 && take_a_crack(&s
, gwp
->key
, "key from DNS TXT"))
1753 else if (keys_from_dns
!= NULL
)
1756 const pubkey_list_t
*kr
;
1758 for (kr
= keys_from_dns
; kr
!= NULL
; kr
= kr
->next
)
1759 if (kr
->key
->alg
== PUBKEY_ALG_RSA
1760 && take_a_crack(&s
, kr
->key
, "key from DNS KEY"))
1763 #endif /* USE_KEYRR */
1766 /* nothing yet: ask for asynch DNS lookup */
1771 /* no acceptable key was found: diagnose */
1773 char id_buf
[BUF_LEN
]; /* arbitrary limit on length of ID reported */
1775 (void) idtoa(&st
->st_connection
->spd
.that
.id
, id_buf
, sizeof(id_buf
));
1777 if (s
.best_ugh
== NULL
)
1779 if (dns_ugh
== NULL
)
1780 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1783 loglog(RC_LOG_SERIOUS
, "no RSA public key known for '%s'"
1784 "; DNS search for KEY failed (%s)"
1787 /* ??? is this the best code there is? */
1788 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1791 if (s
.best_ugh
[0] == '9')
1793 loglog(RC_LOG_SERIOUS
, "%s", s
.best_ugh
+ 1);
1794 /* XXX Could send notification back */
1795 return STF_FAIL
+ INVALID_HASH_INFORMATION
;
1799 if (s
.tried_cnt
== 1)
1801 loglog(RC_LOG_SERIOUS
1802 , "Signature check (on %s) failed (wrong key?); tried%s"
1805 DBG_log("public key for %s failed:"
1806 " decrypted SIG payload into a malformed ECB (%s)"
1807 , id_buf
, s
.best_ugh
+ 1));
1811 loglog(RC_LOG_SERIOUS
1812 , "Signature check (on %s) failed:"
1813 " tried%s keys but none worked."
1816 DBG_log("all %d public keys for %s failed:"
1817 " best decrypted SIG payload into a malformed ECB (%s)"
1818 , s
.tried_cnt
, id_buf
, s
.best_ugh
+ 1));
1820 return STF_FAIL
+ INVALID_KEY_INFORMATION
;
1825 static notification_t
1826 accept_nonce(struct msg_digest
*md
, chunk_t
*dest
, const char *name
)
1828 pb_stream
*nonce_pbs
= &md
->chain
[ISAKMP_NEXT_NONCE
]->pbs
;
1829 size_t len
= pbs_left(nonce_pbs
);
1831 if (len
< MINIMUM_NONCE_SIZE
|| MAXIMUM_NONCE_SIZE
< len
)
1833 loglog(RC_LOG_SERIOUS
, "%s length not between %d and %d"
1834 , name
, MINIMUM_NONCE_SIZE
, MAXIMUM_NONCE_SIZE
);
1835 return PAYLOAD_MALFORMED
; /* ??? */
1837 clonereplacechunk(*dest
, nonce_pbs
->cur
, len
, "nonce");
1838 return NOTHING_WRONG
;
1841 /* encrypt message, sans fixed part of header
1842 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1843 * The theory is that there will be no "backing out", so we commit to IV.
1844 * We also close the pbs.
1847 encrypt_message(pb_stream
*pbs
, struct state
*st
)
1849 const struct encrypt_desc
*e
= st
->st_oakley
.encrypter
;
1850 u_int8_t
*enc_start
= pbs
->start
+ sizeof(struct isakmp_hdr
);
1851 size_t enc_len
= pbs_offset(pbs
) - sizeof(struct isakmp_hdr
);
1853 DBG_cond_dump(DBG_CRYPT
| DBG_RAW
, "encrypting:\n", enc_start
, enc_len
);
1855 /* Pad up to multiple of encryption blocksize.
1856 * See the description associated with the definition of
1857 * struct isakmp_hdr in packet.h.
1860 size_t padding
= pad_up(enc_len
, e
->enc_blocksize
);
1864 if (!out_zero(padding
, pbs
, "encryption padding"))
1870 DBG(DBG_CRYPT
, DBG_log("encrypting using %s", enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1872 /* e->crypt(TRUE, enc_start, enc_len, st); */
1873 crypto_cbc_encrypt(e
, TRUE
, enc_start
, enc_len
, st
);
1876 DBG_cond_dump(DBG_CRYPT
, "next IV:", st
->st_iv
, st
->st_iv_len
);
1881 /* Compute HASH(1), HASH(2) of Quick Mode.
1882 * HASH(1) is part of Quick I1 message.
1883 * HASH(2) is part of Quick R1 message.
1884 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1885 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1888 quick_mode_hash12(u_char
*dest
, const u_char
*start
, const u_char
*roof
1889 , const struct state
*st
, const msgid_t
*msgid
, bool hash2
)
1891 struct hmac_ctx ctx
;
1893 #if 0 /* if desperate to debug hashing */
1894 # define hmac_update(ctx, ptr, len) { \
1895 DBG_dump("hash input", (ptr), (len)); \
1896 (hmac_update)((ctx), (ptr), (len)); \
1898 DBG_dump("hash key", st
->st_skeyid_a
.ptr
, st
->st_skeyid_a
.len
);
1900 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1901 hmac_update(&ctx
, (const void *) msgid
, sizeof(msgid_t
));
1903 hmac_update_chunk(&ctx
, st
->st_ni
); /* include Ni_b in the hash */
1904 hmac_update(&ctx
, start
, roof
-start
);
1905 hmac_final(dest
, &ctx
);
1908 DBG_log("HASH(%d) computed:", hash2
+ 1);
1909 DBG_dump("", dest
, ctx
.hmac_digest_size
));
1910 return ctx
.hmac_digest_size
;
1914 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1915 * Used by: quick_inR1_outI2, quick_inI2
1916 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1917 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1918 * Message ID and Nonces. This is a mistake.
1921 quick_mode_hash3(u_char
*dest
, struct state
*st
)
1923 struct hmac_ctx ctx
;
1925 hmac_init_chunk(&ctx
, st
->st_oakley
.hasher
, st
->st_skeyid_a
);
1926 hmac_update(&ctx
, "\0", 1);
1927 hmac_update(&ctx
, (u_char
*) &st
->st_msgid
, sizeof(st
->st_msgid
));
1928 hmac_update_chunk(&ctx
, st
->st_ni
);
1929 hmac_update_chunk(&ctx
, st
->st_nr
);
1930 hmac_final(dest
, &ctx
);
1931 DBG_cond_dump(DBG_CRYPT
, "HASH(3) computed:", dest
, ctx
.hmac_digest_size
);
1932 return ctx
.hmac_digest_size
;
1935 /* Compute Phase 2 IV.
1936 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1939 init_phase2_iv(struct state
*st
, const msgid_t
*msgid
)
1941 const struct hash_desc
*h
= st
->st_oakley
.hasher
;
1944 DBG_cond_dump(DBG_CRYPT
, "last Phase 1 IV:"
1945 , st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1947 st
->st_new_iv_len
= h
->hash_digest_size
;
1948 passert(st
->st_new_iv_len
<= sizeof(st
->st_new_iv
));
1951 h
->hash_update(&ctx
, st
->st_ph1_iv
, st
->st_ph1_iv_len
);
1952 passert(*msgid
!= 0);
1953 h
->hash_update(&ctx
, (const u_char
*)msgid
, sizeof(*msgid
));
1954 h
->hash_final(st
->st_new_iv
, &ctx
);
1956 DBG_cond_dump(DBG_CRYPT
, "computed Phase 2 IV:"
1957 , st
->st_new_iv
, st
->st_new_iv_len
);
1960 /* Initiate quick mode.
1961 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1962 * (see RFC 2409 "IKE" 5.5)
1963 * Note: this is not called from demux.c
1967 emit_subnet_id(ip_subnet
*net
1968 , u_int8_t np
, u_int8_t protoid
, u_int16_t port
, pb_stream
*outs
)
1970 struct isakmp_ipsec_id id
;
1973 const unsigned char *tbp
;
1977 id
.isaiid_idtype
= subnetishost(net
)
1978 ?
aftoinfo(subnettypeof(net
))->id_addr
1979 : aftoinfo(subnettypeof(net
))->id_subnet
;
1980 id
.isaiid_protoid
= protoid
;
1981 id
.isaiid_port
= port
;
1983 if (!out_struct(&id
, &isakmp_ipsec_identification_desc
, outs
, &id_pbs
))
1986 networkof(net
, &ta
);
1987 tal
= addrbytesptr(&ta
, &tbp
);
1988 if (!out_raw(tbp
, tal
, &id_pbs
, "client network"))
1991 if (!subnetishost(net
))
1994 tal
= addrbytesptr(&ta
, &tbp
);
1995 if (!out_raw(tbp
, tal
, &id_pbs
, "client mask"))
1999 close_output_pbs(&id_pbs
);
2004 quick_outI1(int whack_sock
2005 , struct state
*isakmp_sa
2006 , struct connection
*c
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 clonetochunk(st
->st_tpacket
, reply
.start
, pbs_offset(&reply
)
2195 , "reply packet from quick_outI1");
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.
2222 decode_cert(struct msg_digest
*md
)
2224 struct payload_digest
*p
;
2226 for (p
= md
->chain
[ISAKMP_NEXT_CERT
]; p
!= NULL
; p
= p
->next
)
2228 struct isakmp_cert
*const cert
= &p
->payload
.cert
;
2231 blob
.ptr
= p
->pbs
.cur
;
2232 blob
.len
= pbs_left(&p
->pbs
);
2233 if (cert
->isacert_type
== CERT_X509_SIGNATURE
)
2235 x509cert_t cert
= empty_x509cert
;
2236 if (parse_x509cert(blob
, 0, &cert
))
2238 if (verify_x509cert(&cert
, strict_crl_policy
, &valid_until
))
2241 DBG_log("Public key validated")
2243 add_x509_public_key(&cert
, valid_until
, DAL_SIGNED
);
2247 plog("X.509 certificate rejected");
2249 free_generalNames(cert
.subjectAltName
, FALSE
);
2250 free_generalNames(cert
.crlDistributionPoints
, FALSE
);
2253 plog("Syntax error in X.509 certificate");
2255 else if (cert
->isacert_type
== CERT_PKCS7_WRAPPED_X509
)
2257 x509cert_t
*cert
= NULL
;
2259 if (pkcs7_parse_signedData(blob
, NULL
, &cert
, NULL
, NULL
))
2260 store_x509certs(&cert
, strict_crl_policy
);
2262 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2266 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate payload",
2267 enum_show(&cert_type_names
, cert
->isacert_type
));
2268 DBG_cond_dump_chunk(DBG_PARSING
, "CERT:\n", blob
);
2274 * Decode the CR payload of Phase 1.
2277 decode_cr(struct msg_digest
*md
, struct connection
*c
)
2279 struct payload_digest
*p
;
2281 for (p
= md
->chain
[ISAKMP_NEXT_CR
]; p
!= NULL
; p
= p
->next
)
2283 struct isakmp_cr
*const cr
= &p
->payload
.cr
;
2286 ca_name
.len
= pbs_left(&p
->pbs
);
2287 ca_name
.ptr
= (ca_name
.len
> 0)? p
->pbs
.cur
: NULL
;
2289 DBG_cond_dump_chunk(DBG_PARSING
, "CR", ca_name
);
2291 if (cr
->isacr_type
== CERT_X509_SIGNATURE
)
2295 if (ca_name
.len
> 0)
2299 if (!is_asn1(ca_name
))
2302 gn
= alloc_thing(generalName_t
, "generalName");
2303 clonetochunk(ca_name
, ca_name
.ptr
,ca_name
.len
, "ca name");
2304 gn
->kind
= GN_DIRECTORY_NAME
;
2306 gn
->next
= c
->requested_ca
;
2307 c
->requested_ca
= gn
;
2309 c
->got_certrequest
= TRUE
;
2311 DBG(DBG_PARSING
| DBG_CONTROL
,
2312 dntoa_or_null(buf
, BUF_LEN
, ca_name
, "%any");
2313 DBG_log("requested CA: '%s'", buf
);
2317 loglog(RC_LOG_SERIOUS
, "ignoring %s certificate request payload",
2318 enum_show(&cert_type_names
, cr
->isacr_type
));
2322 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2323 * Note: we may change connections as a result.
2324 * We must be called before SIG or HASH are decoded since we
2325 * may change the peer's RSA key or ID.
2328 decode_peer_id(struct msg_digest
*md
, struct id
*peer
)
2330 struct state
*const st
= md
->st
;
2331 struct payload_digest
*const id_pld
= md
->chain
[ISAKMP_NEXT_ID
];
2332 const pb_stream
*const id_pbs
= &id_pld
->pbs
;
2333 struct isakmp_id
*const id
= &id_pld
->payload
.id
;
2335 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2336 * It talks about the protocol ID and Port fields of the ID
2337 * Payload, but they don't exist as such in Phase 1.
2338 * We use more appropriate names.
2339 * isaid_doi_specific_a is in place of Protocol ID.
2340 * isaid_doi_specific_b is in place of Port.
2341 * Besides, there is no good reason for allowing these to be
2342 * other than 0 in Phase 1.
2344 if ((st
->nat_traversal
& NAT_T_WITH_PORT_FLOATING
)
2345 && id
->isaid_doi_specific_a
== IPPROTO_UDP
2346 && (id
->isaid_doi_specific_b
== 0 || id
->isaid_doi_specific_b
== NAT_T_IKE_FLOAT_PORT
))
2348 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2349 "accepted with port_floating NAT-T",
2350 id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2352 else if (!(id
->isaid_doi_specific_a
== 0 && id
->isaid_doi_specific_b
== 0)
2353 && !(id
->isaid_doi_specific_a
== IPPROTO_UDP
&& id
->isaid_doi_specific_b
== IKE_UDP_PORT
))
2355 loglog(RC_LOG_SERIOUS
, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2357 , IPPROTO_UDP
, IKE_UDP_PORT
2358 , id
->isaid_doi_specific_a
, id
->isaid_doi_specific_b
);
2362 peer
->kind
= id
->isaid_idtype
;
2368 /* failure mode for initaddr is probably inappropriate address length */
2370 err_t ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
)
2371 , peer
->kind
== ID_IPV4_ADDR? AF_INET
: AF_INET6
2376 loglog(RC_LOG_SERIOUS
, "improper %s identification payload: %s"
2377 , enum_show(&ident_names
, peer
->kind
), ugh
);
2378 /* XXX Could send notification back */
2385 if (memchr(id_pbs
->cur
, '@', pbs_left(id_pbs
)) == NULL
)
2387 loglog(RC_LOG_SERIOUS
, "peer's ID_USER_FQDN contains no @");
2392 if (memchr(id_pbs
->cur
, '\0', pbs_left(id_pbs
)) != NULL
)
2394 loglog(RC_LOG_SERIOUS
, "Phase 1 ID Payload of type %s contains a NUL"
2395 , enum_show(&ident_names
, peer
->kind
));
2399 /* ??? ought to do some more sanity check, but what? */
2401 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2405 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2407 DBG_dump_chunk("KEY ID:", peer
->name
));
2410 case ID_DER_ASN1_DN
:
2411 setchunk(peer
->name
, id_pbs
->cur
, pbs_left(id_pbs
));
2413 DBG_dump_chunk("DER ASN1 DN:", peer
->name
));
2417 /* XXX Could send notification back */
2418 loglog(RC_LOG_SERIOUS
, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2419 , enum_show(&ident_names
, peer
->kind
));
2426 idtoa(peer
, buf
, sizeof(buf
));
2427 plog("Peer ID is %s: '%s'",
2428 enum_show(&ident_names
, id
->isaid_idtype
), buf
);
2431 /* check for certificates */
2436 /* Now that we've decoded the ID payload, let's see if we
2437 * need to switch connections.
2438 * We must not switch horses if we initiated:
2439 * - if the initiation was explicit, we'd be ignoring user's intent
2440 * - if opportunistic, we'll lose our HOLD info
2443 switch_connection(struct msg_digest
*md
, struct id
*peer
, bool initiator
)
2445 struct state
*const st
= md
->st
;
2446 struct connection
*c
= st
->st_connection
;
2448 chunk_t peer_ca
= (st
->st_peer_pubkey
!= NULL
)
2449 ? st
->st_peer_pubkey
->issuer
: empty_chunk
;
2454 dntoa_or_null(buf
, BUF_LEN
, peer_ca
, "%none");
2455 DBG_log("peer CA: '%s'", buf
);
2462 if (!same_id(&c
->spd
.that
.id
, peer
))
2464 char expect
[BUF_LEN
]
2467 idtoa(&c
->spd
.that
.id
, expect
, sizeof(expect
));
2468 idtoa(peer
, found
, sizeof(found
));
2469 loglog(RC_LOG_SERIOUS
2470 , "we require peer to have ID '%s', but peer declares '%s'"
2478 dntoa_or_null(buf
, BUF_LEN
, c
->spd
.this.ca
, "%none");
2479 DBG_log("required CA: '%s'", buf
);
2482 if (!trusted_ca(peer_ca
, c
->spd
.that
.ca
, &pathlen
))
2484 loglog(RC_LOG_SERIOUS
2485 , "we don't accept the peer's CA");
2491 struct connection
*r
;
2493 /* check for certificate requests */
2496 r
= refine_host_connection(st
, peer
, peer_ca
);
2498 /* delete the collected certificate requests */
2499 free_generalNames(c
->requested_ca
, TRUE
);
2500 c
->requested_ca
= NULL
;
2506 idtoa(peer
, buf
, sizeof(buf
));
2507 loglog(RC_LOG_SERIOUS
, "no suitable connection for peer '%s'", buf
);
2514 dntoa_or_null(buf
, BUF_LEN
, r
->spd
.this.ca
, "%none");
2515 DBG_log("offered CA: '%s'", buf
);
2520 /* apparently, r is an improvement on c -- replace */
2523 , DBG_log("switched from \"%s\" to \"%s\"", c
->name
, r
->name
));
2524 if (r
->kind
== CK_TEMPLATE
)
2526 /* instantiate it, filling in peer's ID */
2527 r
= rw_instantiate(r
, &c
->spd
.that
.host_addr
2528 , c
->spd
.that
.host_port
, NULL
, peer
);
2531 /* copy certificate request info */
2532 r
->got_certrequest
= c
->got_certrequest
;
2534 st
->st_connection
= r
; /* kill reference to c */
2535 set_cur_connection(r
);
2536 connection_discard(c
);
2538 else if (c
->spd
.that
.has_id_wildcards
)
2540 free_id_content(&c
->spd
.that
.id
);
2541 c
->spd
.that
.id
= *peer
;
2542 c
->spd
.that
.has_id_wildcards
= FALSE
;
2543 unshare_id_content(&c
->spd
.that
.id
);
2549 /* Decode the variable part of an ID packet (during Quick Mode).
2550 * This is designed for packets that identify clients, not peers.
2551 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2552 * (1) it is wrong and (2) we use this value for inband signalling.
2555 decode_net_id(struct isakmp_ipsec_id
*id
2558 , const char *which
)
2560 const struct af_info
*afi
= NULL
;
2562 /* Note: the following may be a pointer into static memory
2563 * that may be recycled, but only if the type is not known.
2564 * That case is disposed of very early -- in the first switch.
2566 const char *idtypename
= enum_show(&ident_names
, id
->isaiid_idtype
);
2568 switch (id
->isaiid_idtype
)
2571 case ID_IPV4_ADDR_SUBNET
:
2572 case ID_IPV4_ADDR_RANGE
:
2573 afi
= &af_inet4_info
;
2576 case ID_IPV6_ADDR_SUBNET
:
2577 case ID_IPV6_ADDR_RANGE
:
2578 afi
= &af_inet6_info
;
2583 /* XXX support more */
2584 loglog(RC_LOG_SERIOUS
, "unsupported ID type %s"
2586 /* XXX Could send notification back */
2590 switch (id
->isaiid_idtype
)
2595 ip_address temp_address
;
2598 ugh
= initaddr(id_pbs
->cur
, pbs_left(id_pbs
), afi
->af
, &temp_address
);
2602 loglog(RC_LOG_SERIOUS
, "%s ID payload %s has wrong length in Quick I1 (%s)"
2603 , which
, idtypename
, ugh
);
2604 /* XXX Could send notification back */
2607 if (isanyaddr(&temp_address
))
2609 loglog(RC_LOG_SERIOUS
, "%s ID payload %s is invalid (%s) in Quick I1"
2610 , which
, idtypename
, ip_str(&temp_address
));
2611 /* XXX Could send notification back */
2614 happy(addrtosubnet(&temp_address
, net
));
2615 DBG(DBG_PARSING
| DBG_CONTROL
2616 , DBG_log("%s is %s", which
, ip_str(&temp_address
)));
2620 case ID_IPV4_ADDR_SUBNET
:
2621 case ID_IPV6_ADDR_SUBNET
:
2623 ip_address temp_address
, temp_mask
;
2626 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2628 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2629 , which
, idtypename
);
2630 /* XXX Could send notification back */
2633 ugh
= initaddr(id_pbs
->cur
2634 , afi
->ia_sz
, afi
->af
, &temp_address
);
2636 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2637 , afi
->ia_sz
, afi
->af
, &temp_mask
);
2639 ugh
= initsubnet(&temp_address
, masktocount(&temp_mask
)
2641 if (ugh
== NULL
&& subnetisnone(net
))
2642 ugh
= "contains only anyaddr";
2645 loglog(RC_LOG_SERIOUS
, "%s ID payload %s bad subnet in Quick I1 (%s)"
2646 , which
, idtypename
, ugh
);
2647 /* XXX Could send notification back */
2650 DBG(DBG_PARSING
| DBG_CONTROL
,
2652 char temp_buff
[SUBNETTOT_BUF
];
2654 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2655 DBG_log("%s is subnet %s", which
, temp_buff
);
2660 case ID_IPV4_ADDR_RANGE
:
2661 case ID_IPV6_ADDR_RANGE
:
2663 ip_address temp_address_from
, temp_address_to
;
2666 if (pbs_left(id_pbs
) != 2 * afi
->ia_sz
)
2668 loglog(RC_LOG_SERIOUS
, "%s ID payload %s wrong length in Quick I1"
2669 , which
, idtypename
);
2670 /* XXX Could send notification back */
2673 ugh
= initaddr(id_pbs
->cur
, afi
->ia_sz
, afi
->af
, &temp_address_from
);
2675 ugh
= initaddr(id_pbs
->cur
+ afi
->ia_sz
2676 , afi
->ia_sz
, afi
->af
, &temp_address_to
);
2679 loglog(RC_LOG_SERIOUS
, "%s ID payload %s malformed (%s) in Quick I1"
2680 , which
, idtypename
, ugh
);
2681 /* XXX Could send notification back */
2685 ugh
= rangetosubnet(&temp_address_from
, &temp_address_to
, net
);
2686 if (ugh
== NULL
&& subnetisnone(net
))
2687 ugh
= "contains only anyaddr";
2690 char temp_buff1
[ADDRTOT_BUF
], temp_buff2
[ADDRTOT_BUF
];
2692 addrtot(&temp_address_from
, 0, temp_buff1
, sizeof(temp_buff1
));
2693 addrtot(&temp_address_to
, 0, temp_buff2
, sizeof(temp_buff2
));
2694 loglog(RC_LOG_SERIOUS
, "%s ID payload in Quick I1, %s"
2695 " %s - %s unacceptable: %s"
2696 , which
, idtypename
, temp_buff1
, temp_buff2
, ugh
);
2699 DBG(DBG_PARSING
| DBG_CONTROL
,
2701 char temp_buff
[SUBNETTOT_BUF
];
2703 subnettot(net
, 0, temp_buff
, sizeof(temp_buff
));
2704 DBG_log("%s is subnet %s (received as range)"
2705 , which
, temp_buff
);
2711 /* set the port selector */
2712 setportof(htons(id
->isaiid_port
), &net
->addr
);
2714 DBG(DBG_PARSING
| DBG_CONTROL
,
2715 DBG_log("%s protocol/port is %d/%d", which
, id
->isaiid_protoid
, id
->isaiid_port
)
2721 /* like decode, but checks that what is received matches what was sent */
2724 check_net_id(struct isakmp_ipsec_id
*id
2729 , const char *which
)
2733 if (!decode_net_id(id
, id_pbs
, &net_temp
, which
))
2736 if (!samesubnet(net
, &net_temp
)
2737 || *protoid
!= id
->isaiid_protoid
|| *port
!= id
->isaiid_port
)
2739 loglog(RC_LOG_SERIOUS
, "%s ID returned doesn't match my proposal", which
);
2746 * look for the existence of a non-expiring preloaded public key
2749 has_preloaded_public_key(struct state
*st
)
2751 struct connection
*c
= st
->st_connection
;
2753 /* do not consider rw connections since
2754 * the peer's identity must be known
2756 if (c
->kind
== CK_PERMANENT
)
2760 /* look for a matching RSA public key */
2761 for (p
= pubkeys
; p
!= NULL
; p
= p
->next
)
2763 pubkey_t
*key
= p
->key
;
2765 if (key
->alg
== PUBKEY_ALG_RSA
&&
2766 same_id(&c
->spd
.that
.id
, &key
->id
) &&
2767 key
->until_time
== UNDEFINED_TIME
)
2769 /* found a preloaded public key */
2778 * Produce the new key material of Quick Mode.
2779 * RFC 2409 "IKE" section 5.5
2780 * specifies how this is to be done.
2783 compute_proto_keymat(struct state
*st
2785 , struct ipsec_proto_info
*pi
)
2787 size_t needed_len
; /* bytes of keying material needed */
2789 /* Add up the requirements for keying material
2790 * (It probably doesn't matter if we produce too much!)
2794 case PROTO_IPSEC_ESP
:
2795 switch (pi
->attrs
.transid
)
2801 needed_len
= DES_CBC_BLOCK_SIZE
;
2804 needed_len
= DES_CBC_BLOCK_SIZE
* 3;
2807 #ifndef NO_KERNEL_ALG
2808 if((needed_len
=kernel_alg_esp_enc_keylen(pi
->attrs
.transid
))>0) {
2809 /* XXX: check key_len "coupling with kernel.c's */
2810 if (pi
->attrs
.key_len
) {
2811 needed_len
=pi
->attrs
.key_len
/8;
2812 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2813 "key_len=%d from peer",
2819 bad_case(pi
->attrs
.transid
);
2822 #ifndef NO_KERNEL_ALG
2823 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2824 "needed_len (after ESP enc)=%d",
2826 if (kernel_alg_esp_auth_ok(pi
->attrs
.auth
, NULL
)) {
2827 needed_len
+= kernel_alg_esp_auth_keylen(pi
->attrs
.auth
);
2830 switch (pi
->attrs
.auth
)
2832 case AUTH_ALGORITHM_NONE
:
2834 case AUTH_ALGORITHM_HMAC_MD5
:
2835 needed_len
+= HMAC_MD5_KEY_LEN
;
2837 case AUTH_ALGORITHM_HMAC_SHA1
:
2838 needed_len
+= HMAC_SHA1_KEY_LEN
;
2840 case AUTH_ALGORITHM_DES_MAC
:
2842 bad_case(pi
->attrs
.auth
);
2844 DBG(DBG_PARSING
, DBG_log("compute_proto_keymat:"
2845 "needed_len (after ESP auth)=%d",
2849 case PROTO_IPSEC_AH
:
2850 switch (pi
->attrs
.transid
)
2853 needed_len
= HMAC_MD5_KEY_LEN
;
2856 needed_len
= HMAC_SHA1_KEY_LEN
;
2859 bad_case(pi
->attrs
.transid
);
2867 pi
->keymat_len
= needed_len
;
2869 /* Allocate space for the keying material.
2870 * Although only needed_len bytes are desired, we
2871 * must round up to a multiple of ctx.hmac_digest_size
2872 * so that our buffer isn't overrun.
2875 struct hmac_ctx ctx_me
, ctx_peer
;
2876 size_t needed_space
; /* space needed for keying material (rounded up) */
2879 hmac_init_chunk(&ctx_me
, st
->st_oakley
.hasher
, st
->st_skeyid_d
);
2880 ctx_peer
= ctx_me
; /* duplicate initial conditions */
2882 needed_space
= needed_len
+ pad_up(needed_len
, ctx_me
.hmac_digest_size
);
2883 replace(pi
->our_keymat
, alloc_bytes(needed_space
, "keymat in compute_keymat()"));
2884 replace(pi
->peer_keymat
, alloc_bytes(needed_space
, "peer_keymat in quick_inI1_outR1()"));
2888 if (st
->st_shared
.ptr
!= NULL
)
2890 /* PFS: include the g^xy */
2891 hmac_update_chunk(&ctx_me
, st
->st_shared
);
2892 hmac_update_chunk(&ctx_peer
, st
->st_shared
);
2894 hmac_update(&ctx_me
, &protoid
, sizeof(protoid
));
2895 hmac_update(&ctx_peer
, &protoid
, sizeof(protoid
));
2897 hmac_update(&ctx_me
, (u_char
*)&pi
->our_spi
, sizeof(pi
->our_spi
));
2898 hmac_update(&ctx_peer
, (u_char
*)&pi
->attrs
.spi
, sizeof(pi
->attrs
.spi
));
2900 hmac_update_chunk(&ctx_me
, st
->st_ni
);
2901 hmac_update_chunk(&ctx_peer
, st
->st_ni
);
2903 hmac_update_chunk(&ctx_me
, st
->st_nr
);
2904 hmac_update_chunk(&ctx_peer
, st
->st_nr
);
2906 hmac_final(pi
->our_keymat
+ i
, &ctx_me
);
2907 hmac_final(pi
->peer_keymat
+ i
, &ctx_peer
);
2909 i
+= ctx_me
.hmac_digest_size
;
2910 if (i
>= needed_space
)
2913 /* more keying material needed: prepare to go around again */
2915 hmac_reinit(&ctx_me
);
2916 hmac_reinit(&ctx_peer
);
2918 hmac_update(&ctx_me
, pi
->our_keymat
+ i
- ctx_me
.hmac_digest_size
2919 , ctx_me
.hmac_digest_size
);
2920 hmac_update(&ctx_peer
, pi
->peer_keymat
+ i
- ctx_peer
.hmac_digest_size
2921 , ctx_peer
.hmac_digest_size
);
2926 DBG_dump("KEYMAT computed:\n", pi
->our_keymat
, pi
->keymat_len
);
2927 DBG_dump("Peer KEYMAT computed:\n", pi
->peer_keymat
, pi
->keymat_len
));
2931 compute_keymats(struct state
*st
)
2933 if (st
->st_ah
.present
)
2934 compute_proto_keymat(st
, PROTO_IPSEC_AH
, &st
->st_ah
);
2935 if (st
->st_esp
.present
)
2936 compute_proto_keymat(st
, PROTO_IPSEC_ESP
, &st
->st_esp
);
2939 /* State Transition Functions.
2941 * The definition of state_microcode_table in demux.c is a good
2942 * overview of these routines.
2944 * - Called from process_packet; result handled by complete_state_transition
2945 * - struct state_microcode member "processor" points to these
2946 * - these routine definitionss are in state order
2947 * - these routines must be restartable from any point of error return:
2948 * beware of memory allocated before any error.
2949 * - output HDR is usually emitted by process_packet (if state_microcode
2950 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2952 * The transition functions' functions include:
2953 * - process and judge payloads
2954 * - update st_iv (result of decryption is in st_new_iv)
2955 * - build reply packet
2958 /* Handle a Main Mode Oakley first packet (responder side).
2962 main_inI1_outR1(struct msg_digest
*md
)
2964 struct payload_digest
*const sa_pd
= md
->chain
[ISAKMP_NEXT_SA
];
2966 struct connection
*c
;
2967 struct isakmp_proposal proposal
;
2968 pb_stream proposal_pbs
;
2970 u_int32_t ipsecdoisit
;
2971 lset_t policy
= LEMPTY
;
2972 int vids_to_send
= 0;
2974 /* We preparse the peer's proposal in order to determine
2975 * the requested authentication policy (RSA or PSK)
2977 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd
->payload
.sa
2978 , &sa_pd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
2980 backup_pbs(&proposal_pbs
);
2981 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2982 , proposal
.isap_notrans
, &policy
));
2983 restore_pbs(&proposal_pbs
);
2985 /* We are only considering candidate connections that match
2986 * the requested authentication policy (RSA or PSK)
2988 c
= find_host_connection(&md
->iface
->addr
, pluto_port
2989 , &md
->sender
, md
->sender_port
, policy
);
2991 if (c
== NULL
&& md
->iface
->ike_float
)
2993 c
= find_host_connection(&md
->iface
->addr
, NAT_T_IKE_FLOAT_PORT
2994 , &md
->sender
, md
->sender_port
, policy
);
2999 /* See if a wildcarded connection can be found.
3000 * We cannot pick the right connection, so we're making a guess.
3001 * All Road Warrior connections are fair game:
3002 * we pick the first we come across (if any).
3003 * If we don't find any, we pick the first opportunistic
3004 * with the smallest subnet that includes the peer.
3005 * There is, of course, no necessary relationship between
3006 * an Initiator's address and that of its client,
3007 * but Food Groups kind of assumes one.
3010 struct connection
*d
;
3012 d
= find_host_connection(&md
->iface
->addr
3013 , pluto_port
, (ip_address
*)NULL
, md
->sender_port
, policy
);
3015 for (; d
!= NULL
; d
= d
->hp_next
)
3017 if (d
->kind
== CK_GROUP
)
3023 if (d
->kind
== CK_TEMPLATE
&& !(d
->policy
& POLICY_OPPO
))
3025 /* must be Road Warrior: we have a winner */
3030 /* Opportunistic or Shunt: pick tightest match */
3031 if (addrinsubnet(&md
->sender
, &d
->spd
.that
.client
)
3032 && (c
== NULL
|| !subnetinsubnet(&c
->spd
.that
.client
, &d
->spd
.that
.client
)))
3040 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3041 " but no connection has been authorized%s%s"
3042 , ip_str(&md
->iface
->addr
), ntohs(portof(&md
->iface
->addr
))
3043 , (policy
!= LEMPTY
) ?
" with policy=" : ""
3044 , (policy
!= LEMPTY
) ?
bitnamesof(sa_policy_bit_names
, policy
) : "");
3045 /* XXX notification is in order! */
3048 else if (c
->kind
!= CK_TEMPLATE
)
3050 loglog(RC_LOG_SERIOUS
, "initial Main Mode message received on %s:%u"
3051 " but \"%s\" forbids connection"
3052 , ip_str(&md
->iface
->addr
), pluto_port
, c
->name
);
3053 /* XXX notification is in order! */
3058 /* Create a temporary connection that is a copy of this one.
3059 * His ID isn't declared yet.
3061 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, NULL
);
3064 else if (c
->kind
== CK_TEMPLATE
)
3066 /* Create an instance
3067 * This is a rare case: wildcard peer ID but static peer IP address
3069 c
= rw_instantiate(c
, &md
->sender
, md
->sender_port
, NULL
, &c
->spd
.that
.id
);
3073 md
->st
= st
= new_state();
3074 st
->st_connection
= c
;
3075 set_cur_state(st
); /* (caller will reset cur_state) */
3076 st
->st_try
= 0; /* not our job to try again from start */
3077 st
->st_policy
= c
->policy
& ~POLICY_IPSEC_MASK
; /* only as accurate as connection */
3079 memcpy(st
->st_icookie
, md
->hdr
.isa_icookie
, COOKIE_SIZE
);
3080 get_cookie(FALSE
, st
->st_rcookie
, COOKIE_SIZE
, &md
->sender
);
3082 insert_state(st
); /* needs cookies, connection, and msgid (0) */
3084 st
->st_doi
= ISAKMP_DOI_IPSEC
;
3085 st
->st_situation
= SIT_IDENTITY_ONLY
; /* We only support this */
3087 if ((c
->kind
== CK_INSTANCE
) && (c
->spd
.that
.host_port
!= pluto_port
))
3089 plog("responding to Main Mode from unknown peer %s:%u"
3090 , ip_str(&c
->spd
.that
.host_addr
), c
->spd
.that
.host_port
);
3092 else if (c
->kind
== CK_INSTANCE
)
3094 plog("responding to Main Mode from unknown peer %s"
3095 , ip_str(&c
->spd
.that
.host_addr
));
3099 plog("responding to Main Mode");
3102 /* parse_isakmp_sa also spits out a winning SA into our reply,
3103 * so we have to build our md->reply and emit HDR before calling it.
3106 /* determine how many Vendor ID payloads we will be sending */
3109 if (SEND_CISCO_UNITY_VID
)
3113 /* always send XAUTH Vendor ID */
3115 /* always send DPD Vendor ID */
3117 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3121 * We can't leave this to comm_handle() because we must
3122 * fill in the cookie.
3125 struct isakmp_hdr r_hdr
= md
->hdr
;
3127 r_hdr
.isa_flags
&= ~ISAKMP_FLAG_COMMIT
; /* we won't ever turn on this bit */
3128 memcpy(r_hdr
.isa_rcookie
, st
->st_rcookie
, COOKIE_SIZE
);
3129 r_hdr
.isa_np
= ISAKMP_NEXT_SA
;
3130 if (!out_struct(&r_hdr
, &isakmp_hdr_desc
, &md
->reply
, &md
->rbody
))
3131 return STF_INTERNAL_ERROR
;
3134 /* start of SA out */
3136 struct isakmp_sa r_sa
= sa_pd
->payload
.sa
;
3138 r_sa
.isasa_np
= vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
;
3140 if (!out_struct(&r_sa
, &isakmp_sa_desc
, &md
->rbody
, &r_sa_pbs
))
3141 return STF_INTERNAL_ERROR
;
3144 /* SA body in and out */
3145 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
, &proposal_pbs
3146 ,&proposal
, &r_sa_pbs
, st
, FALSE
));
3148 /* if enabled send Pluto Vendor ID */
3151 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3152 , &md
->rbody
, VID_STRONGSWAN
))
3154 return STF_INTERNAL_ERROR
;
3158 /* if enabled send Cisco Unity Vendor ID */
3159 if (SEND_CISCO_UNITY_VID
)
3161 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3162 , &md
->rbody
, VID_CISCO_UNITY
))
3164 return STF_INTERNAL_ERROR
;
3169 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3173 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3174 , &md
->rbody
, VID_OPENPGP
))
3176 return STF_INTERNAL_ERROR
;
3180 /* Announce our ability to do eXtended AUTHentication to the peer */
3181 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3182 , &md
->rbody
, VID_MISC_XAUTH
))
3184 return STF_INTERNAL_ERROR
;
3187 /* Announce our ability to do Dead Peer Detection to the peer */
3188 if (!out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3189 , &md
->rbody
, VID_MISC_DPD
))
3191 return STF_INTERNAL_ERROR
;
3194 if (md
->nat_traversal_vid
&& nat_traversal_enabled
)
3196 /* reply if NAT-Traversal draft is supported */
3197 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3199 if (st
->nat_traversal
3200 && !out_vendorid(vids_to_send
-- ? ISAKMP_NEXT_VID
: ISAKMP_NEXT_NONE
3201 , &md
->rbody
, md
->nat_traversal_vid
))
3203 return STF_INTERNAL_ERROR
;
3207 close_message(&md
->rbody
);
3209 /* save initiator SA for HASH */
3210 clonereplacechunk(st
->st_p1isa
, sa_pd
->pbs
.start
, pbs_room(&sa_pd
->pbs
), "sa in main_inI1_outR1()");
3215 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3216 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3218 * The following are not yet implemented:
3219 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3220 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3221 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3223 * We must verify that the proposal received matches one we sent.
3226 main_inR1_outI2(struct msg_digest
*md
)
3228 struct state
*const st
= md
->st
;
3230 u_int8_t np
= ISAKMP_NEXT_NONE
;
3232 /* verify echoed SA */
3234 u_int32_t ipsecdoisit
;
3235 pb_stream proposal_pbs
;
3236 struct isakmp_proposal proposal
;
3237 struct payload_digest
*const sapd
= md
->chain
[ISAKMP_NEXT_SA
];
3239 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd
->payload
.sa
3240 ,&sapd
->pbs
, &ipsecdoisit
, &proposal_pbs
, &proposal
));
3241 if (proposal
.isap_notrans
!= 1)
3243 loglog(RC_LOG_SERIOUS
, "a single Transform is required in a selecting Oakley Proposal; found %u"
3244 , (unsigned)proposal
.isap_notrans
);
3245 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX
);
3247 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3248 , &proposal_pbs
, &proposal
, NULL
, st
, TRUE
));
3251 if (nat_traversal_enabled
&& md
->nat_traversal_vid
)
3253 st
->nat_traversal
= nat_traversal_vid_to_method(md
->nat_traversal_vid
);
3254 plog("enabling possible NAT-traversal with method %s"
3255 , bitnamesof(natt_type_bitnames
, st
->nat_traversal
));
3257 if (st
->nat_traversal
& NAT_T_WITH_NATD
)
3259 np
= (st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
) ?
3260 ISAKMP_NEXT_NATD_RFC
: ISAKMP_NEXT_NATD_DRAFTS
;
3263 /**************** build output packet HDR;KE;Ni ****************/
3266 * We can't leave this to comm_handle() because the isa_np
3267 * depends on the type of Auth (eventually).
3269 echo_hdr(md
, FALSE
, ISAKMP_NEXT_KE
);
3272 if (!build_and_ship_KE(st
, &st
->st_gi
, st
->st_oakley
.group
3273 , &md
->rbody
, ISAKMP_NEXT_NONCE
))
3274 return STF_INTERNAL_ERROR
;