History log of /openbsd-current/sbin/iked/ikev2_msg.c
Revision (<<< Hide revision tags) (Show revision tags >>>) Date Author Comments
# 1.101 02-Mar-2024 tobhe

Trigger retransmission only for fragment 1/x, otherwise each received
fragment can trigger retransmission of the full fragment queue.

From RFC7383, 2.6.1:
"[...] that even MUST only trigger a retransmission of the response message
(fragmented or no) if the Fragment Number field in the received
fragments is set to 1; otherwise, it MUST be ignored."

from markus


Revision tags: OPENBSD_7_4_BASE
# 1.100 04-Aug-2023 claudio

Convert calls to ibuf_length() where it is clear that the ibuf is not
NULL to ibuf_size(). In some cases it is clear that the ibuf pointer
should just be checked for NULL since afterwards a new ibuf is allocated
in its place.
OK tb@


# 1.99 28-Jul-2023 claudio

Implement print_hexbuf() to hexdump the contents of an ibuf.
OK tb@


# 1.98 28-Jul-2023 claudio

Use ibuf_data() instead of accessing the ibuf buf pointer directly.
Also convert some ibuf_add(() calls to ibuf_add_buf() where appropriate.
OK tobhe@ tb@


# 1.97 18-Jul-2023 claudio

Kill ibuf_cat() since there is now ibuf_add_buf() in the official API.
OK tb@ tobhe@


# 1.96 28-Jun-2023 tobhe

Add support to verify X509 chain from CERT payloads.
Encode cert and intermediate CAs in new cert bundle object,
so the information can be passed to the ca process in one step.
Pass untrusted intermediates to X509_verify_cert().

From markus@


# 1.95 13-Jun-2023 tb

iked: introduce and use print_addr()

The vast majority of print_host() callers cast the first argument
(usually a sockaddr_storage *) to (struct sockaddr *) and pass both
a NULL buffer and 0 length. Cast and useless arguments lead to
awkward line wrapping in many places. Clean this up by introducing a
helper. Make this helper take a void pointer, so all casts go away.

ok claudio kn tobhe


# 1.94 06-Jun-2023 claudio

Use ibuf_seek() instead of ibuf_data() + offset constructs. Effect is
the same in these cases.
OK tb@


# 1.93 30-May-2023 claudio

Replace the one use of ibuf_prepend() using a similar ibuf_new() + ibuf_cat()
method but instead of overwriting ibuf internals replace the buf a level up.
Users of ikev2_msg_send() are not allowed to hold and reuse a pointer to
msg_data (which is another footgun to disarm at some point).
OK tb@


# 1.92 23-May-2023 claudio

Replace ibuf_advance() with ibuf_reserve().
OK tobhe@ tb@ kn@


# 1.91 23-May-2023 claudio

Replace ibuf_release() with ibuf_free() since the former just calls the latter
OK kn@ tb@


Revision tags: OPENBSD_7_3_BASE
# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.100 04-Aug-2023 claudio

Convert calls to ibuf_length() where it is clear that the ibuf is not
NULL to ibuf_size(). In some cases it is clear that the ibuf pointer
should just be checked for NULL since afterwards a new ibuf is allocated
in its place.
OK tb@


# 1.99 28-Jul-2023 claudio

Implement print_hexbuf() to hexdump the contents of an ibuf.
OK tb@


# 1.98 28-Jul-2023 claudio

Use ibuf_data() instead of accessing the ibuf buf pointer directly.
Also convert some ibuf_add(() calls to ibuf_add_buf() where appropriate.
OK tobhe@ tb@


# 1.97 18-Jul-2023 claudio

Kill ibuf_cat() since there is now ibuf_add_buf() in the official API.
OK tb@ tobhe@


# 1.96 28-Jun-2023 tobhe

Add support to verify X509 chain from CERT payloads.
Encode cert and intermediate CAs in new cert bundle object,
so the information can be passed to the ca process in one step.
Pass untrusted intermediates to X509_verify_cert().

From markus@


# 1.95 13-Jun-2023 tb

iked: introduce and use print_addr()

The vast majority of print_host() callers cast the first argument
(usually a sockaddr_storage *) to (struct sockaddr *) and pass both
a NULL buffer and 0 length. Cast and useless arguments lead to
awkward line wrapping in many places. Clean this up by introducing a
helper. Make this helper take a void pointer, so all casts go away.

ok claudio kn tobhe


# 1.94 06-Jun-2023 claudio

Use ibuf_seek() instead of ibuf_data() + offset constructs. Effect is
the same in these cases.
OK tb@


# 1.93 30-May-2023 claudio

Replace the one use of ibuf_prepend() using a similar ibuf_new() + ibuf_cat()
method but instead of overwriting ibuf internals replace the buf a level up.
Users of ikev2_msg_send() are not allowed to hold and reuse a pointer to
msg_data (which is another footgun to disarm at some point).
OK tb@


# 1.92 23-May-2023 claudio

Replace ibuf_advance() with ibuf_reserve().
OK tobhe@ tb@ kn@


# 1.91 23-May-2023 claudio

Replace ibuf_release() with ibuf_free() since the former just calls the latter
OK kn@ tb@


Revision tags: OPENBSD_7_3_BASE
# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.99 28-Jul-2023 claudio

Implement print_hexbuf() to hexdump the contents of an ibuf.
OK tb@


# 1.98 28-Jul-2023 claudio

Use ibuf_data() instead of accessing the ibuf buf pointer directly.
Also convert some ibuf_add(() calls to ibuf_add_buf() where appropriate.
OK tobhe@ tb@


# 1.97 18-Jul-2023 claudio

Kill ibuf_cat() since there is now ibuf_add_buf() in the official API.
OK tb@ tobhe@


# 1.96 28-Jun-2023 tobhe

Add support to verify X509 chain from CERT payloads.
Encode cert and intermediate CAs in new cert bundle object,
so the information can be passed to the ca process in one step.
Pass untrusted intermediates to X509_verify_cert().

From markus@


# 1.95 13-Jun-2023 tb

iked: introduce and use print_addr()

The vast majority of print_host() callers cast the first argument
(usually a sockaddr_storage *) to (struct sockaddr *) and pass both
a NULL buffer and 0 length. Cast and useless arguments lead to
awkward line wrapping in many places. Clean this up by introducing a
helper. Make this helper take a void pointer, so all casts go away.

ok claudio kn tobhe


# 1.94 06-Jun-2023 claudio

Use ibuf_seek() instead of ibuf_data() + offset constructs. Effect is
the same in these cases.
OK tb@


# 1.93 30-May-2023 claudio

Replace the one use of ibuf_prepend() using a similar ibuf_new() + ibuf_cat()
method but instead of overwriting ibuf internals replace the buf a level up.
Users of ikev2_msg_send() are not allowed to hold and reuse a pointer to
msg_data (which is another footgun to disarm at some point).
OK tb@


# 1.92 23-May-2023 claudio

Replace ibuf_advance() with ibuf_reserve().
OK tobhe@ tb@ kn@


# 1.91 23-May-2023 claudio

Replace ibuf_release() with ibuf_free() since the former just calls the latter
OK kn@ tb@


Revision tags: OPENBSD_7_3_BASE
# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.97 18-Jul-2023 claudio

Kill ibuf_cat() since there is now ibuf_add_buf() in the official API.
OK tb@ tobhe@


# 1.96 28-Jun-2023 tobhe

Add support to verify X509 chain from CERT payloads.
Encode cert and intermediate CAs in new cert bundle object,
so the information can be passed to the ca process in one step.
Pass untrusted intermediates to X509_verify_cert().

From markus@


# 1.95 13-Jun-2023 tb

iked: introduce and use print_addr()

The vast majority of print_host() callers cast the first argument
(usually a sockaddr_storage *) to (struct sockaddr *) and pass both
a NULL buffer and 0 length. Cast and useless arguments lead to
awkward line wrapping in many places. Clean this up by introducing a
helper. Make this helper take a void pointer, so all casts go away.

ok claudio kn tobhe


# 1.94 06-Jun-2023 claudio

Use ibuf_seek() instead of ibuf_data() + offset constructs. Effect is
the same in these cases.
OK tb@


# 1.93 30-May-2023 claudio

Replace the one use of ibuf_prepend() using a similar ibuf_new() + ibuf_cat()
method but instead of overwriting ibuf internals replace the buf a level up.
Users of ikev2_msg_send() are not allowed to hold and reuse a pointer to
msg_data (which is another footgun to disarm at some point).
OK tb@


# 1.92 23-May-2023 claudio

Replace ibuf_advance() with ibuf_reserve().
OK tobhe@ tb@ kn@


# 1.91 23-May-2023 claudio

Replace ibuf_release() with ibuf_free() since the former just calls the latter
OK kn@ tb@


Revision tags: OPENBSD_7_3_BASE
# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.96 28-Jun-2023 tobhe

Add support to verify X509 chain from CERT payloads.
Encode cert and intermediate CAs in new cert bundle object,
so the information can be passed to the ca process in one step.
Pass untrusted intermediates to X509_verify_cert().

From markus@


# 1.95 13-Jun-2023 tb

iked: introduce and use print_addr()

The vast majority of print_host() callers cast the first argument
(usually a sockaddr_storage *) to (struct sockaddr *) and pass both
a NULL buffer and 0 length. Cast and useless arguments lead to
awkward line wrapping in many places. Clean this up by introducing a
helper. Make this helper take a void pointer, so all casts go away.

ok claudio kn tobhe


# 1.94 06-Jun-2023 claudio

Use ibuf_seek() instead of ibuf_data() + offset constructs. Effect is
the same in these cases.
OK tb@


# 1.93 30-May-2023 claudio

Replace the one use of ibuf_prepend() using a similar ibuf_new() + ibuf_cat()
method but instead of overwriting ibuf internals replace the buf a level up.
Users of ikev2_msg_send() are not allowed to hold and reuse a pointer to
msg_data (which is another footgun to disarm at some point).
OK tb@


# 1.92 23-May-2023 claudio

Replace ibuf_advance() with ibuf_reserve().
OK tobhe@ tb@ kn@


# 1.91 23-May-2023 claudio

Replace ibuf_release() with ibuf_free() since the former just calls the latter
OK kn@ tb@


Revision tags: OPENBSD_7_3_BASE
# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.90 06-Dec-2022 tobhe

Print size_t with %zu.

ok patrick@


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.89 03-Dec-2022 tobhe

Include endian.h where needed for betohXX functions.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.88 11-Nov-2022 mbuhl

In case of an invalid SA resp is passed to ikev2_msg_cleanup without
initialization where the msg_parent field is accessed.
ok tobhe


Revision tags: OPENBSD_7_2_BASE
# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.87 21-Sep-2022 tobhe

Distinguish between retransmit ok and nothing to retransmit. This makes
sure ikes_retransmit_response events don't also increase the
ikes_msg_rcvd_busy counter.

ok markus@


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.86 19-Sep-2022 tobhe

Add iked connection statistics for successful and failed connections, common
error types and other events that help analyze errors in larger setups.
The counters can be printed with 'ikectl show stats'.

ok bluhm@ patrick@
from and ok markus@


Revision tags: OPENBSD_7_1_BASE
# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.85 14-Mar-2022 tobhe

Improve retransmission of message fragments. RFC 7383 states that loss of
a single fragment results in a retransmit of all fragments belonging
to the same message. Instead of treating each fragment as message with
seperate retransmit timer, keep only a single timer for all fragments of
a message and retransmit all fragments in order on timeout.
Improves reliability in case of packet loss when fragmentation is enabled.

Found by and diff from Daniel Herzinger
ok patrick@


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.84 01-Dec-2021 deraadt

whitespace cleanup during review read


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.83 29-Nov-2021 deraadt

sys/param.h was included for MAX(), MIN() and roundup(). make local
copies of MAXIMUM() and MINIMUM() like we have done in 50+ other places,
and also include a roundup()
ok jsg


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.82 27-Nov-2021 tobhe

Rename msg_id to msg_peerid now that we also have msg_localid.

ok patrick@


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.81 26-Nov-2021 patrick

A peer sends both his local id and remote id he expects us to be. So far we
have only looked at the peer's local id, so that we can find a policy with the
matching dstid set. Hence dstid is involved in the decision making. While we
do send out our local id, which the peer will use to verify his policies, we
do not yet make a decision based on the id the peer expects us to have. If you
have two policies configured with only srcid set, we will always pick the same.
To be able to choose a policy that matches the peer's expectations, save the
local id the peer expects us to have and use it during policy lookup.

ok tobhe@


Revision tags: OPENBSD_7_0_BASE
# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.80 07-Sep-2021 tobhe

Fix leak of m if message initialization fails.

ok markus@


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.79 02-Sep-2021 tobhe

style


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.78 01-Sep-2021 tobhe

Add client side support for DNS configuration. Use RTM_PROPOSAL_STATIC
route messages to propose the name server to resolvd(8).
For now, iked will only propose a single name server from the first
established connection.

Automatic name server configuration is enabled by default for policies using
the 'iface' option.

discussed with deraadt@
ok for the DNS parts florian@
ok for the rest patrick@


Revision tags: OPENBSD_6_9_BASE
# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.77 29-Oct-2020 tobhe

Add initial support to request IP addresses as IKEv2 initiator.
At the moment the address is only negotiated and printed to the
log. If 'request addr 0.0.0.0' is configured, any address will
be accepted.

ok patrick@


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.76 09-Oct-2020 tobhe

More unused headers.


# 1.75 09-Oct-2020 tobhe

Remove unused "wait.h" includes.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.74 06-Oct-2020 tobhe

Always allocate hash_keylength() for buffers passed to hash_final() to
make sure there is enough space for the non truncated hash output.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.73 03-Oct-2020 tobhe

React to DELETE notifications only in INFORMATIONAL messages
and move the logic closer to the other INFORMATIONAL payloads.
Add some more sanity checks while we're at it.

ok patrick@


Revision tags: OPENBSD_6_8_BASE
# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.72 26-Sep-2020 tobhe

Cleanup msg_eap in ikev2_msg_cleanup().


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.71 15-Aug-2020 tobhe

Remove dead assignments.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.70 11-Aug-2020 tobhe

Prioritize incoming certificate requests by the order of CERTEQ payloads
in the received message.

ok patrick@


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.69 08-Jul-2020 tobhe

Always try to retransmit on sendtofrom() errors to ensure the SA
is properly cleaned up in ikev2_msg_retransmit_timeout().

ok patrick@


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.68 26-May-2020 tobhe

Add AES-GCM mode ciphers (IANA IDs 19 and 20) for IKEv2.
They can be configured with the new ikesa enc options aes-128-gcm,
aes-256-gcm, aes-128-gcm-12 and aes-256-gcm-12.

Tested with Strongswan by Stephan Mendling and myself
Tested with Juniper SRX by remi@
ok sthen@, patrick@


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.67 14-May-2020 tobhe

Stricter return value checking for EVP_Cipher* calls.

ok patrick@


Revision tags: OPENBSD_6_7_BASE
# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.66 24-Apr-2020 tobhe

Log INFORMATIONAL messages with LOG_DEBUG. They are rarely useful for
debugging and fill up the logs.

ok patrick@ kn@


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.65 17-Apr-2020 tobhe

Log retransmits of sent requests and responses.

ok markus@


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.64 10-Mar-2020 tobhe

Delete dead code in ikev2_msg_valid_ike_sa().

ok markus@


# 1.63 10-Mar-2020 tobhe

Make sure 'e' is NULL initialized to prevent nullptr dereference in
ibuf_release().

ok gerhard@


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.62 22-Jan-2020 deraadt

delete wasteful ;;
ok tedu


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.61 16-Jan-2020 tobhe

Add '-p' command line option which allows to configure
the UDP encapsulation port, similar to isakmpd's '-N' flag.
Being able to change the UDP encapsulation port is useful in cases
where ESP and UDP ports 500 and 4500 are blocked or rate limited.

ok sthen@


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.60 28-Nov-2019 tobhe

Move Notify and Certreq payload handlers after the parser. Modify SA state
only when the full message was parsed successfully.

ok patrick@, "that's working for me" - sthen@


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.59 15-Nov-2019 tobhe

Fix error handling in ikev2_msg_send.

Check sa is not NULL before using it. Use sa consistently instead of
mixing sa and msg->msg_sa. In the error case, if sa is not NULL, save
the message for retransmission and return 0 instead of -1.

ok mikeb@


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.58 13-Nov-2019 tobhe

Log reason whenever a child SA is freed. This makes it easier to
distinguish "valid" reasons to close an SA, such as rekeying,
from errors.

ok sthen@


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.57 11-Nov-2019 tobhe

Cleanup message retransmission handling with new helper functions.

ok patrick@


Revision tags: OPENBSD_6_6_BASE
# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.56 12-Aug-2019 tobhe

Prepend SPI to send and recv log messages to see which line belongs to
which SA. Use IKE specific terms peer and local instead of to and from.

ok reyk@ patrick@


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.55 11-May-2019 patrick

Add support for IKEv2 Message Fragmentation as defined in RFC 7383.

ok sthen@


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.54 10-May-2019 patrick

Enforce messages after IKE_SA_INIT exchange to contain only
encrypted payloads. Also increment message id only for valid
messages.

From Tobias Heider
ok sthen@


Revision tags: OPENBSD_6_3_BASE OPENBSD_6_4_BASE OPENBSD_6_5_BASE
# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.


# 1.53 27-Nov-2017 patrick

Implement MOBIKE (RFC 4555) support in iked(8), with us acting as
responder. In practice this support means that clients like iPhones
can roam in different networks (LTE, WiFi) and change their external
addresses without having to re-do the whole handshake. It allows the
client to choose how and when to change the external tunnel endpoint
addresses on demand, depending on which network is better or even is
connected at all.

ok sthen@
tweaks from jmc@
tested by a handful


Revision tags: OPENBSD_6_2_BASE
# 1.52 26-Apr-2017 henning

cope with IP address changes. before, we were trying to resend the msg
with the no-longer-available address over and over and over, requiring
iked to be restarted eventually. instead, on EADDRNOTAVAIL, schedule
SA deletion so a new one is set up shortly thereafter. ok reyk mikeb


Revision tags: OPENBSD_6_1_BASE
# 1.51 27-Mar-2017 reyk

Add support to reflect the responder IKEv2 COOKIE.

This fixes connecting to Azure VPN and other implementations that
implement the IKEv2 COOKIE mechanism on the responder side. Azure
decides to send you a responder COOKIE after too many connection
attempts - we have to keep it and reflect it to establish a
connection. This implementation is only for the initiator (client)
side, we do not support sending COOKIEs on the responder (server) side
yet.

OK patrick@ mikeb@


# 1.50 27-Mar-2017 reyk

Add support for RFC4754 (ECDSA) and RFC7427 authentication.

These modes provide stronger and more flexible ways for
authentication: while RSA public key auth relies on SHA-1 hashes, the
news modes use SHA2-256 and up to SHA2-512 hashes.

Original diff from markus@ with patches from mikeb@ and me.

OK mikeb@ patrick@


# 1.49 13-Mar-2017 reyk

NAT-T improvements

Move repeated creation of the NAT-T payload into a function, remove
erroneous msg_offset, and improve NAT-T handling.

From and OK markus, OK mikeb


# 1.48 20-Jan-2017 mikeb

Reset various pointers in ikev2_msg_cleanup

From and OK markus@, OK reyk


# 1.47 20-Jan-2017 mikeb

Closed SAs should never be treated as valid

From and OK markus@, OK reyk


# 1.46 04-Sep-2016 vgross

Now that we have IP_SENDSRCADDR, add sendtofrom().

Ok jca@ and reyk@


Revision tags: OPENBSD_5_9_BASE OPENBSD_6_0_BASE
# 1.45 19-Oct-2015 reyk

Remove the ikev1 stub - Since I started iked, it has an empty privsep
process for ISAKMP+IKEv1. I kept it to let somebody either contribute
the old protocol one day, I never intended to implement IKEv1 myself,
or to add a new kind of pipe to isakmpd to hand off IKEv1 messages.
As IKEv2 is widely supported by all major OS and networking vendors
now, I'm happy to scrap the idea of supporting ISAKMP+IKEv1. It is
still possible to use isakmpd for legacy VPNs.

OK mikeb@


# 1.44 15-Oct-2015 mmcc

Remove some unnecessary NULL-checks before free(). Change two bzero()
calls on pf data to explicit_bzero().

ok mikeb@


# 1.43 21-Aug-2015 reyk

Switch iked to C99-style fixed-width integer types.

OK mikeb@


Revision tags: OPENBSD_5_8_BASE
# 1.42 26-Mar-2015 markus

initial support for RFC 7427 signatures, so we are no longer
restricted to SHA1 for RSA signatures. ok mikeb@


Revision tags: OPENBSD_5_7_BASE
# 1.41 15-Feb-2015 tedu

convert bcmp to memcmp
ok doug millert miod


# 1.40 06-Feb-2015 deraadt

unneeded getopt.h


# 1.39 19-Jan-2015 mikeb

Remove unnecessary <netinet/ip_ipsp.h> includes


# 1.38 16-Jan-2015 deraadt

Replace <sys/param.h> with <limits.h> and other less dirty headers where
possible. Annotate <sys/param.h> lines with their current reasons. Switch
to PATH_MAX, NGROUPS_MAX, HOST_NAME_MAX+1, LOGIN_NAME_MAX, etc. Change
MIN() and MAX() to local definitions of MINIMUM() and MAXIMUM() where
sensible to avoid pulling in the pollution. These are the files confirmed
through binary verification.
ok guenther, millert, doug (helped with the verification protocol)


# 1.37 07-Nov-2014 mikeb

Repair initiator with PSK auth

Attempt state transition to VALID (or EAP_VALID) in the
ikev2_ike_auth after we have completed authentication
synchronously (PSK) or asynchronously (X.509 and RSA)
eliminating the need to do so in multiple places and
restoring the correct order for PSK.

ok markus


# 1.36 25-Aug-2014 doug

Delete secret or secret-derived data with explicit_bzero.

concept ok deraadt@
diff looks ok tedu@


Revision tags: OPENBSD_5_6_BASE
# 1.35 07-May-2014 markus

print msgid for debugging; ok reyk & mikeb


# 1.34 06-May-2014 markus

initiate ike sa rekeying (ikesalifetime keyword), re-queue pfkey
events while we are busy initiating child-SAs; ok mikeb@


# 1.33 05-May-2014 markus

the caller of ikev2_msg_retransmit_response already frees the sa; ok mikeb


# 1.32 29-Apr-2014 markus

make sure the state machine only advances if the AUTH payload has
been verified; with & ok mikeb@


# 1.31 22-Apr-2014 reyk

Update iked to use the same proc.c that relayd uses.
Less differences, less code to audit.

ok mikeb@


# 1.30 10-Apr-2014 reyk

Add validation routines to ikev2_pld.c: For each payload type overall
header structure is checked for sanity before copying the header.
Always pass down the number of remaining bytes in the payload or
substructure so we can always ensure to not go beyond actual data.
Also remove the quick parsing step as it does not provide a real
benefit anymore.

From Hans-Joerg Hoexer

ok mikeb@ markus@


Revision tags: OPENBSD_5_5_BASE
# 1.29 17-Feb-2014 reyk

Fix compiler warnings in the format strings: use %zd for ssize_t and
%zu for size_t.

From Andre de Oliveira
With input and OK from blambert@ markus@


# 1.28 24-Jan-2014 mikeb

use a bit saner timer api


# 1.27 03-Dec-2013 markus

never cast to sockaddr_storage, always cast to the abstract 'class' sockaddr
this fixes an out-of-bounds-memcpy in pfkey_process(); ok mikeb@


# 1.26 26-Sep-2013 mikeb

After some manipulations with the buffer, ike message header (hdr)
might no longer point to the same memory as before.

The bug was reported and fix was tested by LEVAI Daniel. Thanks!


Revision tags: OPENBSD_5_4_BASE
# 1.25 21-Mar-2013 deraadt

remove excessive includes


Revision tags: OPENBSD_5_3_BASE
# 1.24 08-Jan-2013 reyk

Remove private CVS tag from an obsolete repository and bump copyright
to 2013 while I'm here... this is my way of saying "happy new year!".


# 1.23 15-Dec-2012 reyk

Remove unused variables.


# 1.22 22-Oct-2012 reyk

Fix NAT-T support in iked, both on the initiator and the responder
side. Also add a new command line option -t to optionally enforce
NAT-T with UDP encapsulation on port 4500.

Tested by mikeb@ and me
ok mikeb@


# 1.21 18-Sep-2012 reyk

update email addresses to match reality.
sure jsg@ mikeb@


Revision tags: OPENBSD_5_2_BASE
# 1.20 27-Jun-2012 mikeb

leftover code re-enqueued the same item on the list multiple times


# 1.19 27-Jun-2012 mikeb

prevent an endless loop


# 1.18 26-Jun-2012 mikeb

improve ikev2_msg_retransmit_timeout


# 1.17 26-Jun-2012 mikeb

compare exchange types as well when looking up a message;
proceed with a response only when the appropriate request
is found.


# 1.16 22-Jun-2012 mikeb

Add initial support for retransmition timeouts and response retries.
This should still be considered an experimental work in progress.


# 1.15 30-May-2012 mikeb

pass a file descriptor in the msg_fd instead of a function argument


# 1.14 24-May-2012 mikeb

don't increment the next expected message id when sending a response back.
while it might look like a step backwards, this fixes up eap negotiation
and bigger changes to this code are in the pipe anyways.


# 1.13 07-May-2012 mikeb

Sync up several defines with RFC 5996. IANA has changed the existing
IKEv2 Payload Type "Encrypted" (E) to "Encrypted and Authenticated" (SK).


Revision tags: OPENBSD_5_0_BASE OPENBSD_5_1_BASE
# 1.12 09-May-2011 reyk

rename functions in proc.c to proc_* and move some code from imsg_util.c to
proc.c. this is the first sync to what i did for relayd but does not include
the multi-instance handling - so no functional change.


Revision tags: OPENBSD_4_9_BASE
# 1.11 21-Jan-2011 reyk

handle empty encrypted payloads (might happen with some informationals)

ok mikeb@


# 1.10 21-Jan-2011 reyk

Reimplement the iked(8) policy evaluation for incoming connections to
use the last matching semantics of PF. The previous rbtree-based
implementation was broken and tried to do a longest prefix match. But
instead of prefix match and using radix-trees to fix it I decided with
mikeb@ to implement it as last matching policy evaluation. The last
matching policy wins; the "quick" keyword can enforce first matching;
additional keywords like "skip" are specific to iked(8). See
iked.conf(5) for more details.

The implementation also uses skip steps based on PF's code. It
significantly speeds up the evaluation of many policies but also adds
a little delay when loading them (only noticeable with thousands of
policies). This allows iked(8) to scale well with thousands of
configured policies but I also liked the fact to have skip steps in
another piece of code.

ok dhartmei@ for using his skip step code under the ISC license in policy.c
ok mikeb@, jmc@


# 1.9 22-Dec-2010 mikeb

child sa rekeying revamp plus numerous bugfixes;
with suggestions and OK from reyk


# 1.8 30-Sep-2010 mikeb

disable padding correctly. therefore we no longer need to supply
additional space in the buffer and just pad input length up to the
block size. finalization is not needed for properly padded data.

kills a bunch of XXX's and an annoying error from openssl.

also, check a result from CipherUpdate while here.

ok reyk


Revision tags: OPENBSD_4_8_BASE
# 1.7 27-Jun-2010 reyk

Instead of modifying and fiddling with the IKE SA in the payload
parsing routines directly, first parse the message and save the parsed
elements in the temporary message struct before validating the
information and taking any other actions on the actual SA. This needs
more testing, but is the cleaner and better approach.


# 1.6 14-Jun-2010 reyk

check if cert is available and valid


# 1.5 14-Jun-2010 reyk

Initial support for initiator mode which allows to run iked as a
"client" or to configure iked to iked (OpenBSD to OpenBSD) IKEv2 VPNs.

It currently only supports psk (pre-shared keys) and no certificates,
doesn't do any rekeying or SA timeouts, and needs more cleanup. So it
is not quite production ready yet - but ready for simple tests...


# 1.4 14-Jun-2010 reyk

restructure code a bit to move closer to initiator mode:
- split responder/initiator- specific code into different functions and use
shared functions for common stuff.
- first parse the received message and store information in the temporary
message struct instead of modifying the ike sa in the parsing code directly.


# 1.3 14-Jun-2010 reyk

cleanup messages and parsed information correctly


# 1.2 14-Jun-2010 reyk

More code for initiator mode (not finished yet)


# 1.1 10-Jun-2010 reyk

i don't like splitting source code in too many source files but ikev2.c
has grown too large, so split it in 3 files and rename a few functions
to organize the code a bit better.